Вопрос

Im trying to create a dynamic Ul Li based on data recieved from the Database

Basically the columns i recieve from the DB are as follows 1.CategoryID 2.ParentCategoryID 3.Href 4.Name.

Now i use the following loop to create my UL.

while (rdr.Read())
{
    if (rdr["ParentCategoryID"].ToString() == "")
    {
        System.Web.UI.HtmlControls.HtmlGenericControl newLI = 
            new System.Web.UI.HtmlControls.HtmlGenericControl("li");

        newLI.Attributes.Add("class", "Item-"+(i+1));
        newLI.ID = "id" + i;
        newLI.InnerHtml = "<a href=" + '"' + 
                             rdr["Href"].ToString() + "/default.aspx" + 
                            '"' +'>' + 
                            "<span>" + rdr["Name"]+"</span>" + "</a>";
        newUL.Controls.Add(newLI);
        i++;
    }
}

In this case I only create the top level of the UL... But this is a multilevel UL

Assuming my inout is as follows

CategoryID ParentCategoryID Href Name

1 NULL /a-d A-C

2 1 /a A

3 1 /b B

4 1 /c C

5 NULL /d-e D-E

6 5 /d D

7 5 /e E

8 NULL /f-g F-G

9 8 /f F

10 8 /g G

Currently my code works until the point whre i get

  • A-C
  • D-E
  • F-G

How do i improve this so i get the sub categories to list under the parent categories?

Это было полезно?

Решение

If you order the items by ParentCategoryID, you can perform a second pass to add all the elements with a non-NULL parent category.

Simply add the new items to the Controls property of the parent.

Usually I use a Dictionary<Key, Value> to keep track of the existing elements and be able to quickly access them by ID.

Last, if you order the whole data by ParentCategoryID with NULL first, then by CategoryID, you should be able to do it in just one while loop.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top