Binding TreeView Dynamically in ASp.NET

Usually TreeView is binded hierarchical data by sitemap, but Sitemap is predefined navigational map. Our business requires to populate database data to TreeView. This article presents how to bind treeview control by datatable dynamically. The example of Populated tree is below.

p1.jpg

private void PopulateParentTree(object sender, EventArgs e)

{

            DataTable dt = new DataTable("Treetbl");

            DataSet ds = new DataSet();

 

            dt.Columns.Add("ID", typeof(int));

            dt.Columns.Add("ParentID", typeof(int));

            dt.Columns.Add("Description", typeof(string));

 

            dt.Rows.Add(0, null, "Root", null);

            dt.Rows.Add(1, 0, "Node1", null);

            dt.Rows.Add(2, 0, "Node2", null);

            dt.Rows.Add(3, 1, "a1", "page1");

            dt.Rows.Add(4, 1, "a2", "page2");

            dt.Rows.Add(5, 2, "b1", "page3");

            dt.Rows.Add(6, 2, "b2", "page4");

            dt.Rows.Add(7, 0, "Close Page", "~/Logout.aspx");

 

            ds.Tables.Add(dt);

            ds.Relations.Add("rsParentChild", ds.Tables["Treetbl"].Columns["ID"], ds.Tables["Treetbl"].Columns["ParentID"]);

          

            if (ds.Tables.Count > 0)

            {

                foreach (DataRow dr in ds.Tables["Treetbl"].Rows)

                {

                    if (dr["ParentID"] == DBNull.Value)

                    {

                        TreeNode pNode = new  

                        TreeNode(dr["Description"].ToString());

                        pNode.PopulateOnDemand = false;

                        pNode.ToggleExpandState();

                        DocsMenu.Nodes.Add(pNode);

                        if (dr.GetChildRows("rsParentChild").Count() > 0)

                        {

                            pNode.Expand();

                            PopulateChildTree(dr, pNode);

                        }

                     }

                }

            }

        } 

 

        private void PopulateChildTree(DataRow dr, TreeNode pNode)

        {

            foreach (DataRow cRow in dr.GetChildRows("rsParentChild"))

            {

                TreeNode cNode = new TreeNode(cRow["Description"].ToString());

                pNode.ChildNodes.Add(cNode);

                if (cRow["ParentID"].ToString() == "0")

                {

                    cNode.ImageUrl = "";

                    PopulateChildTree(cRow, cNode);

                }

            }

        }