Вы находитесь на странице: 1из 13

.

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.

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:

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

.NET Controls: The Tree View Page 1 of 13


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

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:

.NET Controls: The Tree View Page 2 of 13


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

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 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

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

End Sub

Practical Learning: Creating the Root Node


.NET Controls: The Tree View Page 3 of 13
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

.NET Controls: The Tree View Page 4 of 13


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 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.

Practical Learning: Creating the Root Node

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:

.NET Controls: The Tree View Page 5 of 13


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 count As Integer = tvwCountries.GetNodeCount(True)


Me.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 Learning: Creating Child Nodes

.NET Controls: The Tree View Page 6 of 13


1. 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 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

.NET Controls: The Tree View Page 7 of 13


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 Learning: Introducing Node Selection

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

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.

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

.NET Controls: The Tree View Page 8 of 13


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 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

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

.NET Controls: The Tree View Page 9 of 13


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

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()

.NET Controls: The Tree View Page 10 of 13


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 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)

or we can set ImageIndex property of Node object

Practical Learning: Associating Icons With Nodes

1. Display the first form.


In the Toolbox, click ImageList and click the form
2. In the Properties window, click the ellipsis button of the Images field
3. In Image Collection Editor, click Add

.NET Controls: The Tree View Page 11 of 13


4. Locate the folder that contains the current project and display it in the Look In combo box
5. Select StoreDef.ico and click Open
6. 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

7. Click OK
8. In the form, click the tree view and, in the Properties window, set its ImageList to imageList1
9. 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

.....................
Dim nodBabies As TreeNode = New TreeNode("Babies", 2, 3)
.....................

End Sub

10. Execute the application to test it

.NET Controls: The Tree View Page 12 of 13


11. Close the form and return to your programming environment

.NET Controls: The Tree View Page 13 of 13

Вам также может понравиться