When constructing drop-down lists for an ASP.Net page with hierarchical data, it is usually desired to indent each hierarchical entry to illustrate the “tree” of data, e.g.:
Books
Non-fiction
Biographies
Reference
Thrillers
Historical
Spy
CDS
Classical
Dance
The way to do this is by using a non-breaking space   . However, just slapping   in the new ListItem constructor won’t work:
ddl.Items.Add(new ListItem("  Apple", productID.ToString()));
The above would render out this entry in the list:
  Apple (you would see the mark-up as well as the word Apple)
The way around this is to use the hex value of the non-breaking space character, 160. This is obtained by using  , e.g.
ddl.Items.Add(new ListItem("  Apple", productID.ToString()));
However, you will still end up with mark-up similar:
  Apple (you would see the mark-up as well as the word Apple)
This is because the   needs to be decoded as it’s being passed into the ListItem constructor, e.g.:
ddl.Items.Add(new ListItem(HttpUtility.HtmlDecode("  Apple"), productID.ToString()));
This will give you a space-indented entry.
However, this would be of more use:
ddl.Items.Add(new ListItem(HttpUtility.HtmlDecode(MakeSpace(level)) + category.Name, category.CategoryID.ToString()));
where category is an item in a list (ArrayList, List, whatever) and level is the level it should be indented to (more on that next post). The method MakeSpace is as follows:
private string MakeSpace(int level) {
string spaces = String.Empty;
for (int i = 0; i < level; i++) { spaces += "  ";}
return spaces;
}
(if anyone knows of a better way of writing MakeSpace, please let me know)
UPDATE 05/02/09: Ok, there is a better way for MakeSpace, as suggested by my colleague and unofficial mentor, Duncan Godwin:
private string MakeSpace(int level) {
return new String('-', 2 * level).Replace("-", " ");
}
Of course, you could place that directly in the Items.Add method, but I find that less readable.