Introduction to TreeView Control


The Windows Forms Tree View Control helps to display the hierarchy of nodes that can be used to represent the organization structure, file system or any other system which includes hierarchical representation.

For each node added in the hierarchy, user can add a child node to it or a sibling node to it provided there is a parent node for the selected node present.

The article below explores the Tree View Control and depicts the way as how to add a Child node or a sibling node to the selected node.

Case 1: How to add a Child node to a selected node

Create a tree node object and then add it to the selected node in the control.

Below is the code to do that:

TreeNode tnode = new TreeNode(textBox1.Text);
treeView1.SelectedNode.Nodes.Add(tnode);
treeView1.ExpandAll();

if(treeView1.SelectedNode.Nodes.Count > 1 && treeView1.SelectedNode.ForeColor != Color.Blue)

treeView1.SelectedNode.ForeColor = Color.Brown;


Case 2 : How to add a Sibling to a selected node

To add a sibling to a selected node (provided it has a parent node).

Below code implements this concept:

TreeNode tnode = new TreeNode(textBox1.Text);
tnode.ForeColor = Color.Brown;
treeView1.SelectedNode.Parent.Nodes.Add(tnode);



Case3 : Delete a particular selected node

Use the remove method to delete the selected node.

treeView1.SelectedNode.Remove();

Case 4: Use of context Menu

All the above three cases can be performed via use of context menu also.

Thus a user can use this control for displaying the hierarchical structures in his project development and can find this control as of immense use .

For detailed, see attached source code.