Visual Basic: Use a treeview control (Various useful functions)

Platform:Visual Basic
Task:Use a treeview control (Various useful functions)
Discussion:
This example creates a tree and programmatically adds nodes and exposes useful things to do with them such as getting their properties, looping through nodes and highlighting and selecting nodes programmatically
Example:
Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'add two nodes
        TreeView1.Nodes.Add("nodeSkeeter", "Skeeter")
        TreeView1.Nodes.Add("nodePJ", "PJ")

        'add a subnode to the Skeeter node
        TreeView1.Nodes("nodeSkeeter").Nodes.Add("nodePurkey", "Purkey")

        'add a subnode to the PJ node
        TreeView1.Nodes("nodePJ").Nodes.Add("nodeTor", "Tor")
    End Sub

    Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
        ' output the most useful node properties
        txtOut.AppendText("Node Text: " & e.Node.Text & vbNewLine & " Node index: " & e.Node.Index & vbNewLine & " Node Key (reached by the 'name' property of the node (???): " & e.Node.Name & vbNewLine & vbNewLine)
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        'loop through the nodes and output their texts.  Note: this only shows the top level nodes.  You may need to recursively loop through each nodes subnodes as well.
        Dim mnode As TreeNode
        For Each mnode In TreeView1.Nodes
            txtOut.AppendText("Node: " & mnode.Text & vbNewLine)
        Next
    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        'find the node with key 'nodePJ' and open and highlight it
        Dim mnode As TreeNode
        For Each mnode In TreeView1.Nodes
            If mnode.Name = "nodePJ" Then
                mnode.Expand()
                TreeView1.SelectedNode = mnode
                txtOut.AppendText("PJ's node is now selected and highlighted" & vbNewLine & vbNewLine)
            Else
                mnode.Collapse()
            End If
        Next
    End Sub
End Class
Back to Index