Create TreeNode at Runtime

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.

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());





Listing 1

Figure 1: Intended Result

Mayur Dighe