Introduction
This is an article addressing some of the basics
of working with a TreeView control; the article will address dynamically adding
TreeNodes to a TreeView control, searching the nodes to find and highlight a
single node or a collection of nodes matching a search term against the
TreeNode's tag, text, or name properties, and manually or programmatically
selecting nodes.

Figure 1: Searching a TreeView Control by the Text Property.

Figure 2: Searching a TreeView Control by the Name Property.

Figure 3: Searching a TreeView Control by the Name Property.

Figure 4: Creating a Node with Specific Properties.
The Solution
The application solution contains a single Windows Application project comprised; all code supplied in support of this project is contained in two form classes; one is the main form containing the TreeView and a few controls used to display node information (Figures 1, 2, and 3) and to execute searches for a specific node or group of nodes based upon a user supplied search term. The other form class (Figure 4) is used to create new nodes; within the application, this form is displayed by selecting a node from the TreeView and then selecting the "Add Node" option from the context menu.
There is nothing custom or fancy done with any of the TreeView related components in this application; it is merely a demonstration of how to work with a TreeView within the context of a Windows Forms application.
The Code: Form 1 - The Main Form
The main form class is a standard window form with a few controls added; the form contains a split container control; on the left hand side of the control is a TreeView controls, on the right hand side of the splitter are four group boxes; the first group box contains a set of labels and text boxes used to display information about a selected node, the remaining group boxes contain labels, text boxes, and buttons used to conduct different searches of the TreeView's node collection based on the node's text, name, or tag values.
The functionality contained in the class is broken up into several regions; the class begins with the default class declaration:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
' start off by adding a base treeview node
Dim mainNode As New TreeNode()
mainNode.Name = "mainNode"
mainNode.Text = "Main"
Me.treeView1.Nodes.Add(mainNode)
End Sub
The form class constructor creates a main node in the TreeView control; at runtime, the user may select this node (or any child node originating form this node) to add additional nodes to the TreeView. The form class also contains a context menu; this context menu contains two options; one to add a new node, and one to delete an existing node. When a new node is requested, the application opens an instance of the New Node dialog; this dialog forces the user to set the name, text, and tag values for the new node. The tag value can be any object but in this example, the tag is limited to holding an additional string value. Once the values have been collected from the dialog, the new node is populated with the information and added to the selected node of the TreeView.
When a node is deleted, the selected node and all of its children are removed from the TreeView; one thing to note here is, if you are associating an object with a node through its tag; you will want to write the handler to destroy that object prior to deleting the selected node.
#Region "Add and Remove Nodes"
Private Sub cmnuAddNode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuAddNode.Click
Dim n As New Form2()
n.ShowDialog()
Dim nod As New TreeNode()
nod.Name = n.NewNodeName.ToString()
nod.Text = n.NewNodeText.ToString()
nod.Tag = n.NewNodeTag.ToString()
n.Close()
treeView1.SelectedNode.Nodes.Add(nod)
treeView1.SelectedNode.ExpandAll()
End Sub
Private Sub cmnuRemoveNode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmnuRemoveNode.Click
treeView1.SelectedNode.Remove()
End Sub
#End Region
The next region of code is used to handle TreeView events; there are only two events handled in this section; the TreeView's After Select event and the TreeView's click event. The After Select event handler is used to populate the text boxes used to display information from the selected node (its Name, Text, Tag, and Parent text properties. The find functions described later highlight all found nodes in response to a search by setting the background color of each matching node to Yellow; the click event handler for the TreeView is used to remove all such highlighting.
#Region "Treeview Event Handlers"
Private Sub treeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles treeView1.AfterSelect
Try
txtName.Text = ""
txtParentName.Text = ""
txtText.Text = ""
txtTag.Text = ""
txtName.Text = treeView1.SelectedNode.Name.ToString()
txtText.Text = treeView1.SelectedNode.Text.ToString()
txtTag.Text = treeView1.SelectedNode.Tag.ToString()
txtParentName.Text = treeView1.SelectedNode.Parent.Text.ToString()
Catch
'do nothing
End Try
End Sub
Private Sub treeView1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles treeView1.Click
ClearBackColor()
End Sub
#End Region
The next region in the class is used to find a node by its name property. The method of finding a node by its name is the only find function directly supported by the TreeView; if you want to find a node by something other than its name, you will have to write your own methods to do so. This click event handler populates an array of nodes with an array of nodes with matching names. The find method accepts to arguments; the first argument is the search term and the second is a Boolean value used to determine whether or not child nodes should also be included in the search; in this case the search term is collected from a text box on the form and the option of searching child nodes is enabled by setting the second argument to true.
Once the collection of nodes is created; each matching node has its back color set to yellow so as to highlight the node in the TreeView. Prior to setting the back color of the matching nodes, all of the other nodes in the TreeView are set back to having white backgrounds by calling the Clear Back Color method.
#Region "Find Node By Name"
Private Sub btnFindNode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFindNode.Click
ClearBackColor()
Try
Dim tn() As TreeNode = treeView1.Nodes(0).Nodes.Find(txtNodeSearch.Text, True)
Dim i As Integer = 0
For i = 0 To tn.Length
treeView1.SelectedNode = tn(i)
treeView1.SelectedNode.BackColor = Color.Yellow
Next i
Catch
'do nothing
End Try
End Sub
#End Region
The next region of code is used to remove the back color from any nodes highlighting in an earlier search. This process relies on two separate methods. The first method creates an instance of a tree node collection containing all of the nodes in the form's TreeView control. Each of the nodes in the collection is passed to a second method (Clear Recursive); this second method is passed the current node. The Clear Recursive method loops through all of the nodes contained within the passed in nodes node collection and sets the back color of each of those nodes to the color white. Each node is then passed recursively back to the same Clear Recursive method where each node's node collection is processed until there are not more nodes remaining to process. In this way, each node and child node in the entire tree is processed.
While this process is used merely to set each node's back color to white, the same approach may be used whenever the entire tree must be processed; in fact, the remaining search methods will do just that.
#Region "Remove BackColor"
'recursively move through the treeview nodes
'and reset backcolors to white
Private Sub ClearBackColor()
Dim nodes As TreeNodeCollection
nodes = treeView1.Nodes
Dim n As TreeNode
For Each n In nodes

Join the conversation! Your thoughts help the community grow.