Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to load data from database to TreeView

0.00/5 (No votes)
21 Mar 2008 1  
How to load data from database to TreeView

Introduction

How to load data from database into the Treeview control

1-Create two table as show below

Table ParentTable

Table1.jpg

ChildTable

Table2.jpg

2-Add some data

ParentTable

Table3.jpg

ChildTable

Table4.jpg

Drag and drap a TreeView control on the web page

As show below

Image1.jpg

3-Copy the below listed code in the aspx.cs page

//Code Detail          
protected void Page_Load(object sender, EventArgs e)

{

fill_Tree2();

}
        

void fill_Tree2()

{



DataSet PrSet = PDataset("Select * from ParentTable");

TreeView1.Nodes.Clear();

foreach (DataRow dr in PrSet.Tables[0].Rows)

{

TreeNode tnParent = new TreeNode();

tnParent.Text = dr["ParentName"].ToString();

tnParent.Value = dr["ParentID"].ToString(); 

tnParent.PopulateOnDemand = true;

tnParent.ToolTip = "Click to get Child";

tnParent.SelectAction = TreeNodeSelectAction.SelectExpand;

tnParent.Expand();

tnParent.Selected = true;

TreeView1.Nodes.Add(tnParent);

FillChild(tnParent, tnParent.Value);

}

 

}

public void FillChild(TreeNode parent,string ParentId)

{

DataSet ds = PDataset("Select * from ChildTable where ParentId =" + ParentId);

parent.ChildNodes.Clear();

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

{

TreeNode child = new TreeNode();

child.Text = dr["ChildName"].ToString().Trim();

child.Value = dr["ChildId"].ToString().Trim();

if (child.ChildNodes.Count == 0)

{

child.PopulateOnDemand = true;

}

child.ToolTip = "Click to get Child";

child.SelectAction = TreeNodeSelectAction.SelectExpand;

child.CollapseAll();

parent.ChildNodes.Add(child);

}

}

 

protected DataSet PDataset(string Select_Statement)

{

SqlConnection SqlCon = new SqlConnection("Data Source=;Integrated Security=True");

SqlDataAdapter ad = new SqlDataAdapter(Select_Statement, SqlCon);

DataSet ds = new DataSet();

ad.Fill(ds);

return ds;

 

}

Image2.jpg

Points of Interest

Learn new control

History

Keep a running update of any changes or improvements you've made here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here