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.

 

Comments:  4

  • Shamjeed

    Thanks a lot, it worked like charm. I have been searching for this solution for days now…

  • http://www.techbrij.com Brij Mohan

    You are welcome.

  • Craig07

    I am getting an error say that name ‘dtTree’ does not exist in the current context…

  • http://www.techbrij.com Brij Mohan

    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.