Home

.NET Controls: The Tree View

 

The Tree View

 

Introduction

A tree view is a control that resembles an upside down tree and displays a hierarchical list of items. Like a normal tree, a tree view starts in the top section with an object referred to as the root. Under the root, a real tree is made of branches and leaves. In an application, a tree view is only made of branches and each branch is called a node. In real world, a leaf cannot have a branch as its child, only a branch can have another branch as its child and a branch can have a leaf as a child. In an application, a node (any node) can have a node as a child.

Like a real world tree, the branches or nodes of a tree view use a type of relationship so that they are not completely independent. For example, a tree view can be based on a list that has a parent item and other child items that depend on that parent. In real world, if you cut a branch, the branches and leaves attached to it also disappear. This scenario is also valid for a tree view.

Most of the time, a tree has only one root but a tree in an application can have more than one root.

 

 

Tree View Creation

In a Windows application a tree view is primarily a control like any other. To use it in your application, you can click the TreeView button in the Toolbox and click a form or other control in your application. This is programmatically equivalent to declaring a pointer to TreeView, using the new operator to instantiate it and adding it to its container's list of controls through a call to the Controls.Add() method. Here is an example:
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Exercise
    Inherits Form

    Friend WithEvents btnCreate As Button

    Public Sub New()
        Me.InitializeComponent()
    End Sub

    Private Sub InitializeComponent()
        btnCreate = New Button
        btnCreate.Text = "Create"
        btnCreate.Location = New Point(10, 10)

        Me.Controls.Add(btnCreate)
        Text = "Countries Statistics"
        Size = New Size(250, 375)
        StartPosition = FormStartPosition.CenterScreen
    End Sub

    Private Sub btnCreate_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

    End Sub

    Public Shared Sub Main()
        Application.Run(New Exercise)
    End Sub

End Class
Countries Statistics

Using a TreeView variable only adds a rectangular empty control to your application. The next action you probably take is to add one or more branches to the tree.

 

Practical Learning Practical Learning: Introducing  the Tree View Control

  1. Start a new Windows Forms Application named DeptStore1
  2. Change the form's Text to Department Store
  3. In the Windows Forms section of the Toolbox, click TreeView and click the form
  4. Using the Properties window, change its properties as follows:
    (Name): tvwStoreItems
    Anchor: Top, Bottom, Left, Right
  5. Add a Button to the form and change its properties as follows:
    (Name): btnClose
    Text: Close
    Anchor: Bottom, Right

     
  6. Double-click the Close button and implement its Click event as follows:
     
    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    		Handles btnClose.Click
            End
    End Sub
  7. Save all
 

Operations on Tree View's Nodes

 

Introduction to Creating Nodes

To create the nodes of a tree view, Microsoft Visual Studio .NET provides a convenient dialog box you can use at design time. To display it, after adding a TreeView control to a form, you can click the ellipsis button of its Nodes field in the Properties window. This causes the TreeNode Editor to display:

TreeNode Editor

Probably the primary characteristic of a node is the text it displays.

At design time and in the TreeNode Editor, to add a branch, you can click the Add Root button. When you do this, a node with a default but incremental name is created. To edit a node's name, first select it in the Select Node To Edit list, then, in the Label text box, change the string as you wish.

The branches of a tree view are stored in a property called Nodes. The Nodes property is an object based on the TreeNodeCollection class. As its name indicates, the Nodes property carries all of the branches of a tree view. This means that the Nodes property in fact represents a collection. Each member of this collection is called a node and it is an object based on the TreeNode class.

At run time, to create a new node, call the TreeNodeCollection.Add() method which is overloaded with two versions. One of the versions of this method uses the following syntax:

Overloads Public Overridable Function Add(ByVal text As String) As TreeNode

This method takes as argument the string that the branch will display. This method is also the prime candidate to create the root node. Here is an example of calling it:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        tvwCountries.Nodes.Add("World")

End Sub
 

The other version of the TreeNodeCollection.Add() method uses the following syntax:

Overloads Public Overridable Function Add(ByVal node As TreeNode) As Integer

This method takes as argument a TreeNode object. In other words, it expects a complete or semi-complete branch already defined elsewhere.

The TreeNode class is equipped with various constructors you can use to instantiate it. Its default constructor allows you to create a node without primarily giving its details. Another TreeNode constructor has the following syntax:

Public Sub New(ByVal text As String)

This constructor takes as argument the string that the node will display. Here is an example of using it and adding its newly create node to the tree view:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodElement As TreeNode = New TreeNode("World")
        tvwCountries.Nodes.Add(nodElement)

End Sub

We mentioned that the primary characteristic of a node is the text it displays. The text of a node is stored in a property of the TreeNode class and is called Text. This allows you either to specify the string of a node or to retrieve it when needed. Here is an example of setting it:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodElement As TreeNode = New TreeNode
        nodElement.Text = "World"
        tvwCountries.Nodes.Add(nodElement)

End Sub

Just as we called the TreeNodeCollection.Add() method to create a branch, you can call it as many times as necessary to create additional branches. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        tvwCountries.Nodes.Add("World")
        tvwCountries.Nodes.Add("Jupiter")
        tvwCountries.Nodes.Add("Neptune")
        tvwCountries.Nodes.Add("Uranus")

End Sub
 

Alternatively, if you have many branches to add to the tree, you can first create them as an array of TreeNode values, then called the TreeNodeCollection.AddRange() method. The syntax of this method is:

Public Overridable Sub AddRange(ByVal nodes() As TreeNode)

This method takes as argument an array of TreeNode objects. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodPlanets() As TreeNode = { New TreeNode("World"), New TreeNode("Jupiter"), _
             				New TreeNode("Neptune"), New TreeNode("Uranus") }
        tvwCountries.Nodes.AddRange(nodPlanets)

End Sub

Practical LearningPractical Learning: Creating the Root Node

  1. In the Class Name combo box, select (Form1Events)
  2. In the Method Name combo box, select Load
  3. To create the first node of the tree, implement the event as follows:
     
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles MyBase.Load
            Dim nodDeptStore As TreeNode = New TreeNode("Store Items")
    
            Me.tvwStoreItems.Nodes.Add(nodDeptStore)
    End Sub
  4. Execute the application to test the form
     
  5. Close the form

Creating Child Nodes

At design time and in the TreeNode Editor, to create a child node for an existing item, first select it in the Select Node To Edit list, then click the Add Child button. This causes a child node to be created for the selected item. To edit its name, first click it and change the string in the Label text box.

At run time, to create a child node, first get a reference to the node that will be used as its parent. One way you can get this reference is to obtain the returned value of the first version of the TreeNodeCollection.Add() method. As its syntax indicates, this method returns a TreeNode object.

We have used the default constructor of the TreeNode class and the constructor that takes as argument a string. The TreeNode class provides another constructor whose syntax is:

Public Sub New(ByVal text As String, ByVal children() As TreeNode)

The first argument of this method is the string that the new node this constructor creates will display. The second argument is a collection of the child nodes of this branch. The collection is passed as an array. Based on this, you use this constructor to create a new node including its children. After creating the new node, you can pass it to the TreeNodeCollection.Add() method as we did earlier. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodContinents() As TreeNode = {New TreeNode("Africa"), _
               				    New TreeNode("America"), _
               				    New TreeNode("Asia"), _
               				    New TreeNode("Europe")}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

End Sub

Using the same approach, you can create as many branches and their child nodes as you wish. Here is an example:
Imports System
Imports System.Drawing
Imports System.Windows.Forms

Public Class Exercise
    Inherits Form

    Friend WithEvents btnCreate As Button

    Public Sub New()
        Me.InitializeComponent()
    End Sub

    Private Sub InitializeComponent()
        btnCreate = New Button
        btnCreate.Text = "Create"
        btnCreate.Location = New Point(10, 10)

        Me.Controls.Add(btnCreate)
        Text = "Countries Statistics"
        Size = New Size(250, 375)
        StartPosition = FormStartPosition.CenterScreen
    End Sub

    Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 50)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        ' Create a list of some African countries and 
        ' store them in an array named nodAfricans
        Dim nodAfricans() As TreeNode = {New TreeNode("Senegal"), _
                                         New TreeNode("Botswana"), _
                          New TreeNode("Ghana"), _
                          New TreeNode("Morocco")}

        ' Create a list of some American countries and 
        ' store them in an array named nodAmericans
        dim nodAmericans() as	 TreeNode  = { new TreeNode("Canada"), _
		                                   new TreeNode("Jamaica"), _
				   new TreeNode("Colombia")}

        ' Create a list of some European countries and 
        ' store them in an array named nodEuropeans
        Dim nodEuropeans() As TreeNode = {New TreeNode("Italy"), _
                                              New TreeNode("Greece"), _
                New TreeNode("Spain"), _
                New TreeNode("England")}

        ' Create a list of continents, independently
        Dim nodAfrica As TreeNode = New TreeNode("Africa", nodAfricans)
        Dim nodAmerica As TreeNode = New TreeNode("America", nodAmericans)
        Dim nodAsica As TreeNode = New TreeNode("Asia")
        Dim nodEurope As TreeNode = New TreeNode("Europe", nodEuropeans)

        ' Store the list of continents in an array named nodContinents
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodAsica, nodEurope}

        ' Create a branch named nodWorld and store the list of
        ' continents as its child
        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)

        ' Finally, add the nodWorld branch to the tree view
        tvwCountries.Nodes.Add(nodWorld)

    End Sub

    Public Shared Sub Main()
        Application.Run(New Exercise)
    End Sub

End Class

The number of nodes in the TreeNode objects is stored in the TreeNodeCollection.Count property. To get the current number of nodes in the tree view, you can call the TreeView.GetNodeCount() method. Its syntax is:

Public Function GetNodeCount(ByVal includeSubTrees As Boolean) As Integer

Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click

        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 50)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        ' Create a list of some African countries and 
        ' store them in an array named nodAfricans
        Dim nodAfricans() As TreeNode = {New TreeNode("Senegal"), _
                                         New TreeNode("Botswana"), _
                          New TreeNode("Ghana"), _
                          New TreeNode("Morocco")}

        ' Create a list of some American countries and 
        ' store them in an array named nodAmericans
        Dim nodAmericans() As	 TreeNode  = { new TreeNode("Canada"), _
		                                   new TreeNode("Jamaica"), _
				   new TreeNode("Colombia")}

        ' Create a list of some European countries and 
        ' store them in an array named nodEuropeans
        Dim nodEuropeans() As TreeNode = {New TreeNode("Italy"), _
                                              New TreeNode("Greece"), _
                New TreeNode("Spain"), _
                New TreeNode("England")}

        ' Create a list of continents, independently
        Dim nodAfrica As TreeNode = New TreeNode("Africa", nodAfricans)
        Dim nodAmerica As TreeNode = New TreeNode("America", nodAmericans)
        Dim nodAsica As TreeNode = New TreeNode("Asia")
        Dim nodEurope As TreeNode = New TreeNode("Europe", nodEuropeans)

        ' Store the list of continents in an array named nodContinents
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodAsica, nodEurope}

        ' Create a branch named nodWorld and store the list of
        ' continents as its child
        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)

        ' Finally, add the nodWorld branch to the tree view
        tvwCountries.Nodes.Add(nodWorld)

        Dim count As Integer = tvwCountries.GetNodeCount(True)
        Text = "Node Count: " & CStr(count)
    End Sub

If you create a node and add it to a branch that already contains another node, the new node is referred to as a sibling to the existing child node.

 

Practical LearningPractical Learning: Creating Child Nodes

  1. To expand the list, change the Load event of the form as follows:
     
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles MyBase.Load
            ' Create the categories of items for babies
            Dim nodBabiesItems() As	 TreeNode  = { new TreeNode("Health and Care"), _
    				         new TreeNode("Bathing"), _
    			                         new TreeNode("Decorations") }
    
            ' Create the types of pants for women
            Dim nodWomenPants() As TreeNode = {New TreeNode("Casual Pants"), _
                  New TreeNode("Professional Pants"), _
                                     New TreeNode("Jeans"), _
                                     New TreeNode("Shorts")}
    
            ' Create the categories of items for women
            dim nodWomenItems() as TreeNode  = { new TreeNode("Dresses"), _
    	                      new TreeNode("Pants and Jeans", nodWomenPants), _
    				  new TreeNode("Shoes"), _
    				  new TreeNode("Career Wear"), _
    				  new TreeNode("Lingerie") }
    
            ' Create the categories of items for miscellaneous
             dim nodMiscItems() as	 	 TreeNode  = { new TreeNode("Cosmetics"), _
    				  new TreeNode("Travel Gear"), _
    			                      new TreeNode("Jewelry") }
    
            ' Create a list of some of the categories of
            ' thems sold in the store
            Dim nodBabies As TreeNode = New TreeNode("Babies", nodBabiesItems)
            Dim nodTeens As TreeNode = New TreeNode("Teens")
            Dim nodWomen As TreeNode = New TreeNode("Women", nodWomenItems)
            Dim nodMen As TreeNode = New TreeNode("Men")
            Dim nodMisc As TreeNode = New TreeNode("Miscellaneous", nodMiscItems)
            Dim nodCategories() As TreeNode = {nodBabies, nodTeens, nodWomen, nodMen, nodMisc}
    
            ' Create the top node of the tree
            Dim nodDeptStore As TreeNode = New TreeNode("Store Items", nodCategories)
    
            ' Add the top node and its children to the tree
            Me.tvwStoreItems.Nodes.Add(nodDeptStore)
    End Sub
  2. Execute the application to see the result
     
  3. Close the form

The Nodes of a Node

In our introduction, we saw that a node, any node, could have as many nodes as you judge necessary. To support this, the TreeNode class is equipped with a property called Nodes, which, like that of the TreeView class, is based on the TreeNodeCollection class. This allows you to refer to the list of children of the node that this Nodes property belongs to. With this information, you can further create or manipulate child nodes of any node as you wish.

 

Node Selection

Besides looking at a node, probably the primary action a user performs on a tree is to select an item. To select a node in the tree, the user can click it. To programmatically select a node, assign its reference to the TreeView.SelectedNode property. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodAfrica As TreeNode = New TreeNode("Africa")
        Dim nodAmerica As TreeNode = New TreeNode("America")
        Dim nodEurope As TreeNode = New TreeNode("Europe")
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodEurope}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.SelectedNode = nodAmerica
            
End Sub

After selecting a node, the tree view indicates the item selected by highlighting it. In the following picture, the Africa node is selected:

To programmatically find out what item is selected in the tree, get the value of the TreeView.SelectedNode Boolean property. If no node is selected, this property produces null. Alternatively, you can check the value of a node's TreeNode.IsSelected Boolean property to find out if it is currently selected.

Practical LearningPractical Learning: Introducing Node Selection

  1. Just above the line of the btnClose_Click code, declare a global TreeNode variable named nodSelected 
  2. Save all

Node Edition

After locating a node, the user may want to change its text. To change the string of a node, it must be put to edit mode. To do this, you can call the TreeNode.BeginEdit() method. Its syntax is:

Public Sub BeginEdit()

When a node is in edit mode, the caret blinks in its edit box section. The user can then type a new string or edit the existing string. After setting the (new) string, the user can press Enter or may click somewhere. At this time, you need to indicate that the user has finished this operation. To do this, you can call the TreeNode.EndEdit() method. Its syntax is:

Public Sub EndEdit(ByVal cancel As Boolean)

Just before this method, you can check the content of the string that was added or edited. This allows you to accept or reject the change. The argument to the EndEdit() method allows you to validate or cancel the editing action.

 

Node Location

As mentioned already, the nodes of a tree view are stored in a collection of type TreeNodeCollection. Every time you create a new node, it occupies a position inside the tree. Each node is represented by the Item indexed property of this collection. The first node of the tree has an index of 0.

When you call the TreeNodeCollection.Add() method to create a node, the new branch is added at the end of the list of its siblings. If you want, you can add a new child somewhere in the tree. To do this, you would call the TreeNodeCollection.Insert() method. Its syntax is:

public: virtual void Insert(int index, TreeNode* node)

The first argument to this method is the index that the new node will occupy when created. The second argument is a reference to the new node to be created. Here is an example of using it:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodContinents() As TreeNode = {New TreeNode("Africa"), _
                 New TreeNode("America"), _
                 New TreeNode("Asia"), _
                 New TreeNode("Europe")}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.Nodes.Insert(1, New TreeNode("Neptune"))
            
End Sub

Another technique you can use to locate a node consists of using some coordinates. To do this, you can call the TreeView.GetNodeAt() method that is overloaded with two versions whose syntaxes are:

Overloads Public Function GetNodeAt(ByVal pt As Point) As TreeNode
Overloads Public Function GetNodeAt(ByVal x As Integer, ByVal y As Integer) As TreeNode

To use this method, you must know either the Point location or the x and y coordinates of the node. If you provide valid argumentation to this method, it returns a reference to the TreeNode located at the argument. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290

        Controls.Add(tvwCountries)

        Dim nodContinents() As TreeNode = {New TreeNode("Africa"), _
                 New TreeNode("America"), _
                 New TreeNode("Asia"), _
                 New TreeNode("Europe")}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.ExpandAll()

        Dim nodBranch As TreeNode = tvwCountries.GetNodeAt(22, 48)
        Text = nodBranch.Text
            
End Sub
 

After creating a tree, to get a reference to the first child node, you can retrieve the TreeNode.FirstNode property. You would use code as follows:

Dim nodFirst As TreeNode = tvwCountries.Nodes(0).FirstNode
Text = nodFirst.Text

To get a reference to the last child node, retrieve the TreeNode.LastNode property.

To get a reference to the sibling above a node, if any, you can retrieve its TreeNode.PrevNode property. To get a reference to the sibling below a node, if any, you can retrieve its TreeNode.NextNode property.

To find whether a tree view contains a certain node, you can call the TreeNodeCollection.Contains() method. Its syntax is:

Public Function Contains(ByVal node As TreeNode) As Boolean

This method expects as argument a reference to the node to look for. If the tree contains that node, the method returns true. If the node is not found, this method returns false.

 

Practical LearningPractical Learning: Using the Selected Node

  1. In the Class name combo box, select tvwStoreItems
  2. In the Method Name combo box, select MouseDown
  3. Implement the MouseDown event as follows:
     
    Private Sub tvwStoreItems_MouseDown(ByVal sender As Object, _
    	ByVal e As System.Windows.Forms.MouseEventArgs) Handles tvwStoreItems.MouseDown
            Me.nodSelected = Me.tvwStoreItems.GetNodeAt(e.X, e.Y)
    End Sub
  4. To add a new form, on the main menu, click Project -> Add Windows Forms...
  5. Set the Name to NewCategory and click Open
  6. Design the form as follows:
     
    Department Store - New Category: Form Design
    Control Name Text Other Properties
    Label   New Category:  
    TextBox txtNewCategory   Modifiers: Public
    Button btnOK OK DialogResult: OK
    Button btnCancel Cancel DialogResult: Cancel
    Form   New Make AcceptButton: btnOK
    CancelButton: btnCancel
    FormBorderStyle: FixedDialog
    MaximizeBox: False
    MinimizeBox: False
    ShowInTaskbar: False
    StartPosition: CenterScreen
  7. Display the first form (Form1.vb (Design)). In the Windows Forms section of the Toolbox, click ContextMenu and click the form
  8. On the form, click ContextMenu and click Type Here. Create three menu items as follows:
     
    Text (Name) Shortcut
    New Category mnuNewCategory CtrlN
    Delete mnuDelCategory Del
    Remove all Items mnuDeleteAll ShiftDel
  9. On the form, click the tree view. In the Properties window, set its ContextMenu to ContextMenu1
  10. Right-click the form and click View Code
  11. In the Class Name combo box, select mnNewCategory
  12. In the Method Name combo box, select Click
  13. Implement the event as follows:
     
    Private Sub mnuNewCategory_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles mnuNewCategory.Click
            If nodSelected Is Nothing Then Exit Sub
    
            Me.tvwStoreItems.SelectedNode = nodSelected
            Dim dlgCategory As NewCategory = New NewCategory
    
            If dlgCategory.ShowDialog() = DialogResult.OK Then
                If dlgCategory.txtNewCategory.Text = "" Then
                    Exit Sub
                End If
            End If
    
            Me.tvwStoreItems.SelectedNode.Nodes.Add(dlgCategory.txtNewCategory.Text)
    End Sub
     
  14. Execute the application
  15. Click the + button
  16. Right-click Women in the tree and click New Category
     
  17. In the New Category dialog box, type Skirts
     
  18. Press Enter
     
  19. Close the form and return to your programming environment

The Path to a Node

After a node has been added to a tree, it holds a position relative to its parent and its existence depends on that parent. To keep track of its "ancestry", each node has a path that can be used to identify its parent and its grand-parent(s), if any. To know the path of a node from itself to the root, you can access its TreeNode.FullPath property. This property produces a string made of sections separated by a specific character identified as the TreeView.PathSeparator property. By default, this character is the backslash, following the conventions of the operating system. If you want to use a different character or string, assign it to the PathSeparator property. To know what character or string a tree view is using as the separator, you can retrieve the value of its PathSeparator property.

 

Deleting Nodes

When a tree contains a few nodes, the user may want to delete some of them, for any reason. To delete a node, you can call the TreeNodeCollection.Remove() method. Its syntax is:

Public Sub Remove(ByVal node As TreeNode)

This method expects a reference to the node you want to delete. Another solution you can use would consist of locating the index of the node and using it. To do this, you would call the TreeNodeCollection.RemoveAt() method. Its syntax is:

Public Overridable Sub RemoveAt(ByVal index As Integer) Implements IList.RemoveAt

When calling this method, pass the index of the node to be deleted. If you are already at that node and you want to remove it, you can call the TreeNode.Remove() method. Its syntax is:

Public Sub Remove()

One of the characteristics of a tree in the real world is that, if you cut a branch, the other branches attached to it and their leaves are cut too. In the same way, if you call any of these Remove() or RemoveAt() methods to delete a node, its children would be deleted too.

To remove all nodes of a tree view, you can call the TreeNodeCollection.Clear() method. Its syntax is:

Public Overridable Sub Clear() Implements IList.Clear

This method is used to get rid of all nodes of a tree.

 

Practical LearningPractical Learning: Deleting a Node

  1. In the Class Name combo box, select mnuDelCategory
  2. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub mnuDelCategory_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles mnuDelCategory.Click
            ' Make sure a node is selected
            If nodSelected.IsSelected() = True Then
                Me.nodSelected.Remove()
            End If
        End Sub
  3. In the Class Name combo box, select mnuDeleteAll
  4. In the Method Name combo box, select Click and implement the event as follows:
     
    Private Sub mnuDeleteAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
    		Handles mnuDeleteAll.Click
            Me.tvwStoreItems.Nodes.Clear()
    End Sub
  5. Execute the application and try deleting an item

Visual Feedback of Nodes

 

Hot Tracking

In order to select an item, the user must click it or navigate to it using the keyboard. Alternative, if you want, you can cause the items to be underlined when the mouse passes over them:

To produce this effect, you can set to true the TreeView.HotTracking Boolean property. Its default value is false.

The Intermediary Lines of Related Nodes

As mentioned already, a tree view appears as a list of items arranged like a tree. This implies a relationship of parent-child among the items in the control. To indicate this relationship between two nodes, a line is drawn from one to another. Based on this, a line from a node on top to another node under it indicates that the one on top is the parent to the one under it.

The presence or absence of the lines among related nodes is controlled by the TreeView.ShowLines Boolean property. By default, this property is set to true. If this property is set to false, the lines among the nodes would not display. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290
        tvwCountries.ShowLines = False

        Controls.Add(tvwCountries)

        Dim nodAfrica As TreeNode = New TreeNode("Africa")
        Dim nodAmerica As TreeNode = New TreeNode("America")
        Dim nodEurope As TreeNode = New TreeNode("Europe")
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodEurope}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.SelectedNode = nodAmerica
            
End Sub

The Root Lines

If you create a tree that has more than one root, a line is drawn among those root nodes. Here is an example:

The presence or absence of this type of line is controlled by the TreeView.ShowRootLines Boolean property.

Node Indentation

Indentation is the ability for a child node to be aligned to the right with regards to its parent. The general distance from the left border of the parent to the left border of the children is partially controlled by the TreeView.Indent property which is an integer. If the default distance doesn't suit you, you can change it by assigning a positive number to the control's Indent property.

Full Row Selection

When the user clicks an item, that node becomes highlighted for the length of its string. If you want, you can show the highlighting on the selected node but from the left to the right borders of the tree view. To do this, you can set the TreeView.FullRowSelect Boolean property to true. Its default value is false. For the TreeView.FullRowSelect property to work, the ShowLines property must be set to false. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290
        tvwCountries.ShowLines = False
        tvwCountries.FullRowSelect = True

        Controls.Add(tvwCountries)

        Dim nodAfrica As TreeNode = New TreeNode("Africa")
        Dim nodAmerica As TreeNode = New TreeNode("America")
        Dim nodEurope As TreeNode = New TreeNode("Europe")
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodEurope}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.SelectedNode = nodAmerica
            
End Sub
 

Hiding Selection After Losing Focus

We saw that, to select an item, the user can click it. If the user clicks another control, the node that was selected in the tree view loses its highlighting because the control has lost focus. When the focus moves to another control, if you want the selected node of the tree view to preserve its highlighting, set to false the TreeView.HideSelection Boolean property. Its default value is true.

The + and - Buttons

At this time, we have seen that some nodes have children and some don't. When a node has at least one child, the node indicates this by displaying a + button. If the user clicks the + button, the node expands, displays a list of its children, and the button becomes -. The presence or absence of the + and - buttons is controlled by the TreeView.ShowPlusMinus Boolean property. By default, this property is set to true. If you don't want the parent nodes to display the + or - button, set this property to false.

Expanding and Collapsing Tree Nodes

When a node displays a + button and the user clicks that button, the node displays its child(ren). This action is referred to as expanding the node. To programmatically expand a node, call its TreeNode.Expand() method. Its syntax is:

Public Sub Expand()

This method only expands the node that calls it but if its children have their own children, they are not expanded.  To expand a node and its children that have nodes, you can call its TreeNode.ExpandAll() method. Its syntax is:

Public Sub ExpandAll()

To find out if a node is expanded, check the value of its TreeNode.IsExpanded property.

To expand other nodes of the tree view, the user can continue clicking each node that has a + button as necessary. To programmatically expand all nodes of a tree view, call its TreeView.ExpandAll() method. Its syntax is:

Public Sub ExpandAll()

If a node is displaying a - button, it indicates that it is showing the list of its children. To hide the list, the user can click the - button. This action is referred to as collapsing the node. To programmatically collapse a node, call its TreeNode.Collapse() method whose syntax is:

Public Sub Collapse()

The user can do this for each node that is expanded. To programmatically collapse all nodes of a tree view, call its TreeView.CollapseAll() method. Its syntax is:

Public Sub CollapseAll()

Tree Nodes and Check Boxes

Besides the strings (and some small pictures as we will see later), the nodes of a tree view can display a check box on their left side. The presence or absence of the check box is controlled by the CheckBoxes Boolean property whose default value is false. If you want to display the check boxes, set this property to true. Here is an example:

Private Sub btnCreate_Click(ByVal sender As System.Object, _
                                ByVal e As System.EventArgs) Handles btnCreate.Click
        Dim tvwCountries As TreeView = New TreeView
        tvwCountries.Location = New Point(10, 40)
        tvwCountries.Width = 220
        tvwCountries.Height = 290
        tvwCountries.CheckBoxes = True

        Controls.Add(tvwCountries)

        Dim nodAfrica As TreeNode = New TreeNode("Africa")
        Dim nodAmerica As TreeNode = New TreeNode("America")
        Dim nodEurope As TreeNode = New TreeNode("Europe")
        Dim nodContinents() As TreeNode = {nodAfrica, nodAmerica, nodEurope}

        Dim nodWorld As TreeNode = New TreeNode("World", nodContinents)
        tvwCountries.Nodes.Add(nodWorld)

        tvwCountries.SelectedNode = nodAmerica
            
    End Sub

If you equip the nodes with check boxes, the user can click an item to select it independently of the check box. The user can also click the check box, which would place a check mark in the box. To programmatically check the box, you can assign a true value to the node's Checked property.

When a check mark has been placed in a node's check box, the tree view fires an AfterCheck event, which is handled by the TreeViewEventHandler delegate. The AfterCheck event is carried by the TreeViewEventArgs class. One of properties of this class is called Action, which specifies why or how the event occurred. The Action property is in fact a value based on the TreeViewAction enumerator. Its members are:

ByKeyboard: This indicates that the event was fired by pressing a key

ByMouse: This indicates that the event was fired based on an action of the mouse

Collapse: This indicates that event was fired when the tree collapsed

Expand: This indicates that the event was fired when the tree expanded

Unknown: None of the above reasons (probably) caused the event, but the event was fired

The other property of the TreeViewEventArgs class is called Node. This member is of type TreeNode. It carries a reference to the node that fired the event, whether it was clicked, checked, expanded, or collapsed.

To programmatically find out if a node is checked, check the value of its Checked property.

 

Tree Nodes and Icons

Each of the nodes we have used so far displayed a simple piece of text. To enhance the appearance of a node, besides its text, you can display a small icon to the left of its string. To do this, you must first create an ImageList control and assign it to the TreeView.ImageList property.

When creating a node, if you plan to display an icon next to it, you can use the following constructor of the TreeNode class:

Public Sub New(ByVal text As String, _
   	         ByVal imageIndex As Integer, _
   	         ByVal selectedImageIndex As Integer)

This constructor allows you to specify the text that the node will display, the index of the picture it will use in the ImageList property, and the picture it will display when it is selected.

If you are creating a node with its children and you want to specify its pictures, use the following constructor of the TreeNode class:

Public Sub New(ByVal text As String, _
	         ByVal imageIndex As Integer, _
 	         ByVal selectedImageIndex As Integer, _
 	         ByVal children() As TreeNode)

Just as done previously, after defining the TreeNode object, you can add it to the tree by passing it to the TreeNodeCollection.Add() method. In the same way, you can create an array of TreeNode objects and pass it to the TreeNodeCollection.AddRange() method.

 

Practical LearningPractical Learning: Associating Icons With Nodes

  1. To create an icon, on the main menu, click Project . Add Resource... In the Add Resource dialog box, click Icon and click New
  2. Right-click a white area in the main window and click New Item Type... In the New Icon Image Type dialog box, make sure 16x16, 16 colors is selected and click OK
  3. In the Properties window, change the Filename to StoreDef.ico and design the icon as follows:
     
  4. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  5. Right-click the white area and click Delete Image Type
  6. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  7. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  8. In the Properties window, change the Filename to StoreSel.ico and design it as follows:
     
  9. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  10. Right-click the white area and click Delete Image Type
  11. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  12. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  13. In the Properties window, change the Filename to CatDef.ico and design it as follows:
     
  14. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  15. Right-click the white area and click Delete Image Type
  16. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  17. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  18. In the Properties window, change the Filename to CatSel.ico and design it as follows:
     
  19. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  20. Right-click the white area and click Delete Image Type
  21. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  22. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  23. In the Properties window, change the Filename to GroupDef.ico and design it as follows:
     
  24. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  25. Right-click the white area and click Delete Image Type
  26. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  27. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  28. In the Properties window, change the Filename to GroupSel.ico 
  29.  and design it as follows:
     
  30. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  31. Right-click the white area and click Delete Image Type
  32. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  33. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  34. In the Properties window, change the Filename to LevelDef.ico and design it as follows:
     
  35. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  36. Right-click the white area and click Delete Image Type
  37. To create another icon, on the main menu, click Project . Add Resource...In the Add Resource dialog box, click Icon and click New
  38. As done above, display the New Icon Image dialog box and select 16x16, 16 colors
  39. In the Properties window, change the Filename to LevelSel.ico and design it as follows:
     
  40. Right-click the white area . Current Icon Image Types . 32x32, 16 Colors
  41. Right-click the white area and click Delete Image Type
  42. Save all
  43. Display the first form.
    In the Toolbox, click ImageList and click the form
  44. In the Properties window, click the ellipsis button of the Images field
  45. In Image Collection Editor, click Add
  46. Locate the folder that contains the current project and display it in the Look In combo box
  47. Select StoreDef.ico and click Open
  48. In the same way, add the other pictures in the following order: StoreSel.ico, StoreSel.ico, CatDef.ico, CatSel.ico, GroupDef.ico, GroupSel.ico, LevelDef.ico, LevelSel.ico
     
  49. Click OK
  50. In the form, click the tree view and, in the Properties window, set its ImageList to imageList1
  51. Double-click an unoccupied area of the form and change its Load event as follows:
     
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Load
            ' Create the categories of items for babies
           dim nodBabiesItems() as	 TreeNode  = { new TreeNode("Health and Care", 4, 5), _
    				  new TreeNode("Bathing", 4, 5), _
    			                      new TreeNode("Decorations", 4, 5) }
    
            ' Create the types of pants for women
            Dim nodWomenPants() As TreeNode = {New TreeNode("Casual Pants", 6, 7), _
                  New TreeNode("Professional Pants", 6, 7), _
                                     New TreeNode("Jeans", 6, 7), _
                                     New TreeNode("Shorts", 6, 7)}
    
            ' Create the categories of items for women
           dim nodWomenItems() as	 TreeNode  = { new TreeNode("Dresses", 4, 5), _
    			          new TreeNode("Pants and Jeans", 4, 5, nodWomenPants), _
    				  new TreeNode("Shoes", 4, 5), _
    				  new TreeNode("Career Wear", 4, 5), _
    				  new TreeNode("Lingerie", 4, 5) }
    
            ' Create the categories of items for miscellaneous
            dim nodMiscItems() as TreeNode  = { new TreeNode("Cosmetics", 4, 5), _
    				  new TreeNode("Travel Gear", 4, 5), _
    			                      new TreeNode("Jewelry", 4, 5) }
    
            ' Create a list of some of the categories of
            ' items sold in the store
            Dim nodBabies As TreeNode = New TreeNode("Babies", 2, 3, nodBabiesItems)
            Dim nodTeens As TreeNode = New TreeNode("Teens", 2, 3)
            Dim nodWomen As TreeNode = New TreeNode("Women", 2, 3, nodWomenItems)
            Dim nodMen As TreeNode = New TreeNode("Men", 2, 3)
            Dim nodMisc As TreeNode = New TreeNode("Miscellaneous", 2, 3, nodMiscItems)
            Dim nodCategories() As TreeNode = {nodBabies, nodTeens, nodWomen, nodMen, nodMisc}
    
            ' Create the top node of the tree
            Dim nodDeptStore As TreeNode = New TreeNode("Store Items", 0, 1, nodCategories)
    
            ' Add the top node and its children to the tree
            Me.tvwStoreItems.Nodes.Add(nodDeptStore)
    End Sub
  52. Execute the application to test it
     
    Department Store
  53. Close the form and return to your programming environment

 

Home Copyright © 2005-2012 FunctionX