Aug 30, 2010

Display Hierarchical Data with TreeView in ASP.NET 2.0

When there are no Large Amounts of Data then it is not good to connect database, fetch data and add to treeview node again and again for child/sub nodes. It can be done in single attempt. In following example, ID=-1 for root nodes.

First we need to fetch all data from database:

string sourceConnection = "<Connection string>";
DataTable dtTree = new DataTable();  
using (SqlConnection connection = new SqlConnection(sourceConnection))
SqlCommand dbCommand = new SqlCommand();
dbCommand.CommandText = "Select ID,ParentID,Title from tblTree";
dbCommand.CommandType = CommandType.Text;
dbCommand.Connection = connection;
SqlDataAdapter da = new SqlDataAdapter(dbCommand);
AddNodes(-1, treeView1.Nodes);

"AddNodes" Method adds nodes in treeview and based on recursion.

void AddNodes(int id, TreeNodeCollection tn)
foreach (DataRow dr in dtTree.Select("ParentID = " + id))
TreeNode sub = new TreeNode(dr["Title"].ToString(), dr["ID"].ToString());                
AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);

Hope, It helps.