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.
i couldn’t load the root node. any idea?
thank you.
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.
I am getting an error say that name ‘dtTree’ does not exist in the current context…
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.
Thanks a lot, it worked like charm. I have been searching for this solution for days now…
You are welcome.