TreeView in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This lesson describes the TreeView control


The TreeView control displays a hierarchical data set graphically, using the TreeNode objects to represent the items it contains.

The control's Nodes collection contains references to the top-level objects called its root nodes.

    ' create the nodes
    Dim settingsroot = New TreeNode("Settings")
    settingsroot.Nodes.Add("Database Stuff")
    settingsroot.Nodes.Add("General Settings")

    Dim stundetsroot = New TreeNode("All Students")
    stundetsroot.Nodes.Add("Search Students")
    stundetsroot.Nodes.Add("General Settings")

    Dim universityroot = New TreeNode("University")
    universityroot.Nodes.Add("Lecture Rooms")

    ' add the nodes

You can also add the nodes using the TreeNode Editor.

treenode editor

You can assign each of the TreeNode objects an icon to display.

If the TreeView control's ImageList property is set to an ImageList control, you can set a node's ImageIndex property to the index of the image in the ImageList that the node should display.

Set the node's SelectedImageIndex to the index of the image that the control should display when the node is selected.

To collapse all of the control's nodes you use the CollapseAll method, and to expand all of the control's nodes you use the ExpandAll method.

    Private Sub TreeViewControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub

The control provides a series of events that fire before and after you take certain actions.

For example, when you click a node's check box, the control raises its BeforeCheck event, changes the node's checked state, and then raises its AfterCheck event.

The other actions that have similar Before and After event handlers are Collapse, Expand, LabelEdit, and Select, and each of the Before event handlers provides a parameter that the code can set to cancel the event.

    Private Sub TreeView1_BeforeCheck(sender As Object, e As TreeViewCancelEventArgs) _
                Handles TreeView1.BeforeCheck
        e.Cancel = True
    End Sub

Previous Lesson | Next Lesson

Share This

Home | About | Contact | Privacy Policy

Copyright 2018 - All Rights Reserved.