TreeView in Visual Basic .NET

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

This lesson describes the TreeView control


TreeView

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")
    stundetsroot.Nodes.Add("Grades")

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

    ' add the nodes
    TreeView1.Nodes.Add(settingsroot)
    TreeView1.Nodes.Add(stundetsroot)
    TreeView1.Nodes.Add(universityroot)


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
        TreeView1.ExpandAll()
    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 visual-basic-tutorials.com 2017 - All Rights Reserved.