This tip shows how to create a TreeNode to TreeView Control at runtime in C#.
Following code snippet creates a TreeNode and its sub nodes to TreeView Control programmatically. Firstly, it creates a 2 TreeNode Object named ParentNode & ChildNode and then adds 4 nodes and accordingly sub nodes to the TreeNode Object using for loop. ExpandAll () Method expands all the nodes present in the specified TreeView Control on Execution.
Figure 1: Intended Result
The article demonstrates how to populate TreeView Control using SqlDataSource at runtime in C#.NET. We can achieve intended result by simply executing SqlCommand Object either by ExecuteReader or ExecuteNonQuery method.
The TreeView control has a Nodes collection with root TreeNode objects. Each TreeNode in turn has its own Nodes collection that holds more than one child TreeNode.
Step 1: Declaration of Connection, Command, and DataReader object
Step 2: Now, whatever the code required to written for populating the SqlDataSource to the TreeView Control you can place it either into the click, load etc. event handlers.
Step 3: We need to create two TreeNode Objects as follows…
Step 4: Now pass the SqlQuery as an argument of SqlCommand Object and stored the values into SqlDataReader Object.
Step 5: Now retrieve the values from SqlDataReader and adds it to the Child Nodes of Nodes Collection of TreeView Control.