Rendering an unordered list using asp.net

You could do something like this in code and then output the result to a Literal control on your page:

int lastDepth = -1;
int numUL = 0;

StringBuilder output = new StringBuilder();


foreach (DataRow row in yourDataTable.Rows) {

    int currentDepth = row["Depth"];

    if (lastDepth < currentDepth) {
        output.append("<ul>");
        numUL++
    }
    else if (lastDepth > currentDepth) {
        output.append("</li></ul></li>");
        numUL--
    }
    else if (lastDepth > -1) {
        output.append("</li>");
    }

    output.appendformat("<li class=\"depth-{1}\">{0}", row["name"], currentDepth);

    lastDepth = currentDepth;
}

for (int i = 1;i <= numUL;i++)
{
    output.append("</li></ul>");
}



yourLiteralControl.Text = output.toString();

Update: I made it so that it will put in a css class on the list items related to the depth as requested in the comments.


Use the Repeater Control.

Samples:

  • Sample 1
  • Sample 2

MSDN Documentation

Edit: Didn't notice the part about depth, use the Treeview Control instead, look at the part about binding to a database.


Unless you're using .NET 2.0 you should use the ListView Control.

Using ASP.NET 3.5's ListView and DataPager Controls: Displaying Data with the ListView