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);
da.Fill(dtTree);
da.Dispose();
dbCommand.Dispose();
connection.Dispose();
}
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());                
tn.Add(sub);
AddNodes(Convert.ToInt32(sub.Value), sub.ChildNodes);
}
}

Hope, It helps.

6 comments

  1. hi, this one is an old article, but can you give me the full code? Cause I don’t know why dtTree not found.

    Thank you so much, really appreciated.

    1. You need to define dtTree as member variable of the Page. Assign value on page_load event and use it in AddNodes method. In my code, Both sourceConnection and dtTree are defined before page_load event.

Leave a Reply

Your email address will not be published. Required fields are marked *