
Introduction
In this article, I have tried to explain the basic usages of TreeView
control. Because of this, I'm giving a sample code to show the basic operations (such as add parent and child nodes) on TreeView
.
This article is just written to be a reference when you need to use the TreeView
control in your VB.NET applications.
Implementation of the Sample
Here, you will find the necessary source code of the application the main form of which is shown above. Each event procedure in the whole source code is explained separately.
The code for "Add Parent" button
It is only one line and creates a parent node by taking its name from the textbox.
Private Sub AddParent_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles AddParent.Click
TView.Nodes.Add(Text1.Text)
End Sub
The code for "Add Child" button
It is only one line and creates a child node by taking its name from the textbox. It creates a child node under the selected parent node. You can create a child node under another child node.
Private Sub AddChild_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles AddChild.Click
TView.SelectedNode.Nodes.Add(Text1.Text)
End Sub
The code for "Delete" button
It is only one line again and deletes the selected node whether it is a parent or child. Moreover, you can delete any parent node completely whether it has child nodes.
Private Sub DeleteNode_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles DeleteNode.Click
TView.SelectedNode.Remove()
End Sub
Important Points
- Do not forget that if any node has a child, the node is being a parent node of the child.
- Any parent node can be a child node of a one level up node.
- If you delete any parent node, the parent node will be deleted completely with its child nodes. If you do not want this to be happen, you will need an extra statement to check the condition of the parent node.
- In this sample, before you add a new child, you should select a node (as a parent) by clicking on it. Otherwise it may give an error. Moreover, it is the same for the delete operation and you should select the node that you want to delete.
- This sample application is prepared to be a reference while using the
TreeView
control in your VB.NET applications.
Have a nice day!