How to Create TreeNode at Runtime in C#.NET

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.

 

 

          public void CreateTree()

          {

                   TreeNode ParentNode = treeView1.Nodes.Add("Parent Node");

                   TreeNode ChildeNode;

            

                    for (int i = 1; i <= 4; i++)

                   {

                             ChildeNode = ParentNode.Nodes.Add("Child Node " + i.ToString());

                             for (int j = 1; j <= i; j++)

                             {

                                                ChildeNode.Nodes.Add("Sub Node " + j.ToString());

                             }

                   }

                   ParentNode.ExpandAll();

        }

Listing 1

 

 

image002.jpg

Figure 1: Intended Result

 

Ebook Download
View all
Learn
View all