Section 14.9. TreeView Control


14.9. treeView Control

The treeView control displays nodes hierarchically in a tree. Traditionally, nodes are objects that contain values and can refer to other nodes. A parent node contains child nodes, and the child nodes can be parents to other nodes. Two child nodes that have the same parent node are considered sibling nodes. A tree is a collection of nodes, usually organized in a hierarchical manner. The first parent node of a tree is the root node (a treeView can have multiple roots). For example, the file system of a computer can be represented as a tree. The top-level directory (perhaps C:\) would be the root, each subfolder of C:\ would be a child node and each child folder could have its own children. treeView controls are useful for displaying hierarchal information, such as the file structure that we just mentioned. We cover nodes and trees in greater detail in Chapter 24, Data Structures. Figure 14.24 displays a sample treeView control on a Form.

Figure 14.24. treeView displaying a sample tree.


A parent node can be expanded or collapsed by clicking the plus box or minus box to its left. Nodes without children do not have these boxes.

The nodes in a TReeView are instances of class treeNode. Each treeNode has a Nodes collection (type TReeNodeCollection), which contains a list of other TReeNodesknown as its children. The Parent property returns a reference to the parent node (or Nothing if the node is a root node). Figure 14.25 and Fig. 14.26 list the common properties of treeViews and treeNodes, common treeNode methods and a common treeView event.

Figure 14.25. TReeView properties and an event.

TReeView properties and an event

Description

Common Properties

CheckBoxes

Indicates whether CheckBoxes appear next to nodes. A value of True displays CheckBoxes. The default value is False.

ImageList

Specifies an ImageList object containing the node icons. An ImageList object is a collection that contains Image objects.

Nodes

Lists the collection of treeNodes in the control. It contains methods Add (adds a treeNode object), Clear (deletes the entire collection) and Remove (deletes a specific node). Removing a parent node deletes all of its children.

SelectedNode

The selected node.

Common Event (Event arguments TReeViewEventArgs)

AfterSelect

Generated after selected node changes.


Figure 14.26. treeNode properties and methods.

treeNode properties and methods

Description

Common Properties

Checked

Indicates whether the treeNode is checked (CheckBoxes property must be set to TRue in the parent treeView).

FirstNode

Specifies the first node in the Nodes collection (i.e., the first child in the tree).

Full Path

Indicates the path of the node, start ing at the root of the tree.

ImageIndex

Specifies the index of the image shown when the node is deselected.

LastNode

Specifies the last node in the Nodes collection (i.e., the last child in the tree).

NextNode

Next sibling node.

Nodes

Collection of TReeNodes contained in the current node (i.e., all the children of the current node). The Nodes collection has methods Add (adds a treeNode object), Clear (deletes the entire collection) and Remove (deletes a specific node). Removing a parent node deletes all of its children.

Parent

Parent node of the current node.

PrevNode

Previous sibling node.

SlectedImageIndex

Specifies the index of the image to use when the node is selected.

Text

Specifies the treeNode's text.

Common Methods

Collapse

Collapses a node.

Expand

Expands a node.

ExpandAll

Expands all the children of a node.

GetNodeCount

Returns the number of child nodes.


To add nodes to the treeView visually, click the ellipsis next to the Nodes property in the Properties window. This opens the TreeNode Editor (Fig. 14.27), which displays an empty tree representing the treeView. There are Buttons to create a root, and to add or delete a node. To the right are the properties of current node. Here you can rename the node.

Figure 14.27. TreeNode Editor.


To add nodes programmatically, first create a root node. Create a new treeNode object and pass it a String to display. Then call method Add to add this new treeNode to the treeView's Nodes collection. Thus, to add a root node to treeView myTreeView, write

 myTreeView.Nodes.Add(rootLabel) 


where myTreeView is the treeView to which we are adding nodes, and rootLabel is the text to display in myTreeView. To add children to a root node, add new treeNodes to its Nodes collection. We select the appropriate root node from the TReeView by writing

 myTreeView.Nodes(myIndex) 


where myIndex is the root node's index in myTreeView's Nodes collection. We add nodes to child nodes through the same process by which we added root nodes to myTreeView. To add a child to the root node at index myIndex, write

 myTreeView.Nodes(myIndex).Nodes.Add(childNodeText) 


Class FrmTreeViewDirectoryStructure (Fig. 14.28) uses a TReeView to display the contents of a directory chosen by the user. A TextBox and a Button are used to specify the directory. First, enter the full path of the directory you want to display. Then click the Button to set the specified directory as the root node in the TReeView. Each subdirectory of this directory becomes a child node. This layout is similar to the one used in Windows Explorer. Folders can be expanded or collapsed by clicking the plus or minus boxes that appear to their left.

Figure 14.28. treeView used to display directories.

  1  ' Fig. 14.28: FrmTreeViewDirectoryStructure.vb  2  ' Using TreeView to display directory structure.  3  Imports System.IO  4  5  Public Class FrmTreeViewDirectoryStructure  6     ' clear treDirectory, then call PopulateTreeView  7     Private Sub btnEnter_Click(ByVal sender As System.Object, _  8        ByVal e As System.EventArgs) Handles btnEnter.Click  9 10        treDirectory.Nodes.Clear() ' clear all nodes 11 12        ' if the directory specified by the user exists, fill in the 13        ' TreeView; otherwise, display an error message 14        If (Directory.Exists(txtInput.Text)) Then 15           ' add full path name to directoryTreeView 16           treDirectory.Nodes.Add(txtInput.Text) 17 18           ' insert subfolders 19           PopulateTreeView(txtInput.Text, treDirectory.Nodes(0)) 20        Else ' display error MessageBox if directory not found 21           MessageBox.Show(txtInput.Text & " could not be found.", _ 22              "Directory Not Found", MessageBoxButtons.OK, _ 23              MessageBoxIcon.Error) 24        End If 25     End Sub ' btnEnter 26 27     ' populate current node with subdirectories 28     Private Sub PopulateTreeView( _ 29        ByVal directoryValue As String, ByVal parentNode As TreeNode) 30        ' array stores all subdirectories in the directory 31        Dim directoryArray As String() = _          32           Directory.GetDirectories(directoryValue) 33 34        ' populate current node with subdirectories 35        Try 36           ' check to see if any subdirectories are present 37          If directoryArray.Length <> 0 Then 38             ' for every subdirectory, create new TreeNode, 39             ' add as a child of current node and recursively 40             ' populate child nodes with subdirectories 41             For Each directory As String In directoryArray 42                 ' obtain last part of path name from the full path name 43                 ' by finding the last occurence of "\" and returning the 44                 ' part of the path name that comes after this occurrence 45                 Dim directoryName As String = directory.Substring( _ 46                    directory.LastIndexOf("\") + 1) 47 48                 ' create TreeNode for current directory 49                 Dim myNode As TreeNode = New TreeNode(directoryName) 50 51                 ' add current directory node to parent node 52                 parentNode.Nodes.Add(myNode) 53 54                 ' recursively populate every subdirectory 55                 PopulateTreeView(directory, myNode) 56              Next 57           End If 58        Catch e As UnauthorizedAccessException 59           parentNode.Nodes.Add("Access denied") 60        End Try 61     End Sub ' PopulateTreeView 62  End Class ' FrmTreeViewDirectoryStructure 

(a)

(b)

When the user clicks the btnEnter, all the nodes in treDirectory are cleared (line 10). Then the path entered in txtInput is used to create the root node. Line 16 adds the directory to treDirectory as the root node, and line 19 calls method PopulateTreeView (lines 2861), which receives as arguments a directory (as a String) and a parent node (as a treeNode). Method PopulateTreeView then creates child nodes corresponding to the subdirectories of the directory it receives as an argument.

PopulateTreeView (lines 2861) obtains a list of subdirectories, using method Getdirectories of class Directory (namespace System.IO ) in lines 3132. Method Getdirectories receives the current directory (as a String ) and returns an array of Strings representing its subdirectories. If a directory is not accessible for security reasons, an UnauthorizedAccessException is thrown. Lines 5859 catch this exception and add a node containing "Access Denied."

If there are accessible subdirectories, lines 4546 use the Substring method to increase readability by shortening the full path name to just the directory name. Next, each String in the directoryArray is used to create a new child node (line 49). We use method Add (line 52) to add each child node to the parent. PopulateTreeView calls itself recursively on each subdirectory (line 55), which eventually populates the treeView with the entire directory structure. Note that our recursive algorithm may cause a delay when the program loads directories with many subdirectories. However, once the folder names are added to the appropriate Nodes collection, they can be expanded and collapsed without delay. In the next section, we present an alternative algorithm to solve this problem.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net