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.

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)
Nagarathna kPosted Aug 18, 2020, 2:23 AM
I donot need hardcode i need the data from database