Kubi
Kubi

Reputation: 2169

How to dynamically create a tree view in asp.net?

I have 2 database tables named Categories and SubCategories and I want to create an Unordered List inside my asp.net web form like a tree view like

ul li a href=""CategoryDynamicData/li ul li SubCategoryDynamicData li .. .. ..

Any algorithms for that ? I couldn't nest 2 repeaters ?

Upvotes: 0

Views: 4013

Answers (3)

Brij
Brij

Reputation: 6122

you can display Hierarchical Data with TreeView. See following sample to bind data in treeview:
http://urenjoy.blogspot.com/2009/08/display-hierarchical-data-with-treeview.html

Upvotes: 0

Kubi
Kubi

Reputation: 2169

OK It seems not the best way but here how I solved this... Hope it helps others :)

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        using (ProjectsDataContext dc = new ProjectsDataContext())
        {
            var categories = from cats in dc.Categories
                             select cats;

            sb.Append("<ul id=\"sitemap\" class=\"sitemap\">");

            foreach (Category c in categories)
            {
                sb.Append("<li><a href=\"ShowCategory.aspx?CategoryID="+c.CategoryID +"\">"+ c.Name+"</a>");

                var subcategories = from subs in dc.SubCategories
                                    where (subs.Category.Name == c.Name)
                                    select subs;

                sb.Append("<ul>");

                foreach (SubCategory s in subcategories)
                {
                    sb.Append("<li><a href=\"../ShowSubCategory.aspx?SubCategoryID=" + s.SubCategoryID + "\">" + s.Name + "</a></li>");
                }
                sb.Append("</ul></li>");

            }

            sb.Append("</ul>");
        }


        lala.Text = sb.ToString();
    }

Upvotes: 0

Robert Harvey
Robert Harvey

Reputation: 180787

Out of curiosity, why won't asp:TreeView work for you?

You could use a jQuery plugin, like the Treeview plugin. It works exactly as you described, by using ul and li to represent the tree branches and leaves.

Upvotes: 2

Related Questions