Rafael Kayser Smiderle
Rafael Kayser Smiderle

Reputation: 690

Treeview population dynamically

I need to populate a treeview in asp.net and I need a recursive function to insert all nodes and child nodes on the treeview.

I have two methods:

GetRootPage()

GetPagesByParent(Page parent) -> returns a IEnumerable<Page> with the page childs.

Anyone can help me with the recursive logic to build the tree?

Upvotes: 0

Views: 1249

Answers (1)

James Johnson
James Johnson

Reputation: 46067

I sincerely hope this isn't a homework question. That being said, something like this should get you started:

Disclaimer: I have not tested or verified this, and it is intended only to serve as a rough example

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var pages = GetPagesByParent(Page);
        if (pages.Count() > 0)
        {
            var roots = pages.Where(p => p.Parent == null);
            foreach (var root in roots)
            {
                //add the root nodes to the tree
                var rootNode = new TreeNode(root.Title);
                tree.Nodes.Add(rootNode);

                //kick off the recursive population
                PopulateChildNodes(pages, root, rootNode);
            }
        }
    }
}

protected void PopulateChildNodes(IEnumerable<Page> pages, Page parent, TreeNode parentNode)
{
    var childPages = pages.Where(p => p.Parent == parent);
    foreach (var page in pages)
    {
        var pageNode = new TreeNode(page.Title);
        parentNode.Nodes.Add(pageNode);

        //populate the children of the pageNode
        PopulateChildNodes(pages, page, pageNode);
    }
}

Upvotes: 1

Related Questions