devxlogo

Making the Most of the VB TreeView Control

Making the Most of the VB TreeView Control

he TreeView control is one of the most flexible Windows controls. It displays hierarchical data and lets users navigate through the hierarchy by expanding and collapsing nodes at will. I may be slightly biased, but I think it’s an awesome tool for building functional Windows interfaces. Yet TreeView controls haven’t received the attention they deserve, probably because, as delivered, they’re not easy to use in many real-world situations, where users must be able to insert, delete, edit, rearrange, and save the items. This tutorial shows you how to solve these problems.

The downloadable TVEdit sample application (see Figure 1), demonstrates a range of TreeView techniques. It lets you populate a TreeView control at run time, edit the node text, drag and drop nodes, moving them from one position to another, persist the nodes to an XML file and reload a TreeView control from the persisted XML file at some future point.

Define Keyboard Mappings
When you alter the default behavior of a user-interface control, you must consider not only how users access new or modified features with the mouse, but also how you can let them use the keyboard. By default, the TreeView control supports these keys:
  • Pressing the up and down (or left and right) arrow keys move the selected item up or down to the next visible control, whether on the same or a different level.
  • Pressing the Enter key collapses or expands a node, depending on its current state. When you’re on an expanded node and you press the right arrow key, the selection moves to the next lower visible node. If needed, the control expands collapsed nodes, all the way to a terminal node. If you select a collapsed node and then press the left arrow key, the selection moves to its parent node. Keep pressing the left arrow key on collapsed nodes to move all the way to a root node.

The project’s code doesn’t interfere with these basic navigational keystrokes. But the default keystroke set doesn’t include the ones necessary to let users edit the control’s contents; therefore, the project recognizes several additional keystrokes required to perform basic editing operations, as follows:

  • Inserting new nodes. To add a new node under the selected one, press the Ins key. To add a new root node, press Control+Insert. After you add a new node, the code places the control in edit mode automatically, letting you edit the new node’s label. To end any edit operation, press the Enter key. After you finish editing the new node’s label, the program selects the parent node, so you can add a new node under the same parent by pressing the Insert key again.
  • Editing node labels. To edit a node’s label, press the Space bar, or the F2 key (the Enter key might be a better choice, but by default, Enter expands or collapses a node, depending on its current state). The control places the selected node’s label in edit mode. You end the edit operation by pressing Enter.
  • Deleting nodes. To delete a node, select it and press the Delete key.
  • Dragging nodes. You can change the hierarchy of the nodes by dragging a node and dropping it on another node. The control moves the original node to its new position as a child of the target node (the node on which the drop operation took place). If you want to copy a node under a new parent, hold the Shift key as you drag and drop it. If the selected node contains child nodes of its own, the entire hierarchy under the selected node will be copied or moved.

Implement Keystroke Handlers
Now that you’ve defined the keystrokes that control the new features, you must implement them in code. In the sample, the TreeView control’s KeyDown event handler processes all editing operations that involve keystrokes. It consists of a Select Case block with a separate Case command for each keystroke you’re interested in.

When a user presses the space bar, the code places the selected node in edit mode by calling its StartLabelEdit method. When the user presses the Delete key, the code removes the selected node by calling the TreeView.Nodes collection’s Remove method. When the user presses the Insert key, the code adds a new node as a child of the selected node and places it in edit mode with the following statements:

   Set insNode = TreeView1.Nodes.Add _      (TreeView1.SelectedItem, tvwChild)   insNode.Text = ""   TreeView1.StartLabelEdit

To terminate edit mode, the user must press Enter again. If the user presses Control+Insert, the code adds a new root node and places it in edit mode:

   If Shift And vbCtrlMask Then       Set insNode = TreeView1.Nodes.Add()       insNode.Selected = True       TreeView1.StartLabelEdit   End If

Each node must have a key?a string identifier. The sample project creates a key for newly added or edited nodes when the edit operation ends by generating a random number between 1 and 10000000, prefixed with the “K” character (the key can’t be a numeric value). Because the Rnd() function doesn’t generate unique random values, the code generates the key within a loop, testing each time by attempting to set the Key property. If the generated key is already in use, VB raises an error, in which case the code simply repeats the loop to choose a different number.

   Dim Repeat As Boolean   Repeat = True   While Repeat       On Error Resume Next       TreeView1.SelectedItem.Key = "K" & 1 + _          Int(Rnd() * 10000000)        If Err.Number = 0 Then Repeat = False   Wend

The editing operations themselves are straightforward and completely keyboard-driven.Implementing Node Drag-and-Drop
The most interesting aspect of the application is the ability to alter the hierarchy itself with drag and drop operations. The TreeView control doesn’t support drag and drop operations natively on its own items, so I’ve chosen to program the OLE drag and drop events. First, you must set the control’s OLEDragMode property to Automatic and the OLEDropMode property to Manual. When the user starts dragging a node, the control fires the OLEStartDrag event:

   Private Sub TreeView1_OLEStartDrag( _      Data As MSComctlLib.DataObject, _      AllowedEffects As Long)      Data.Clear      If Not Me.TreeView1.SelectedItem Is Nothing Then           Data.SetData Me.TreeView1.SelectedItem.Key, _        vbCFText      End If   End Sub

You set the Data argument of the event handler to the selected node’s Key property. You’ll see in a moment how the code uses that value. While the user is dragging the node around, VB generates the OLEDragOver event (the sample code ignores this event for controls other than the TreeView control on the form). Listing 1 shows the handler for the OLEDragOver event. As users drag items over existing nodes, they aren’t highlighted automatically, so you must highlight each node by setting the TreeView control’s DropHighlight property to the appropriate node. To determine the node under the cursor, call the control’s HitTest method, and pass the coordinates of the cursor as arguments:

   TreeView1.DropHighlight = TreeView1.HitTest(x, y)

Dragging nodes over nodes currently visible is no problem, but it’s harder to drag a node to a node that isn’t visible in the TreeView control’s window. To do that, you have to force the TreeView control to scroll up or down as the drag operation approaches the top or bottom edge of the control. The TVEdit project uses a Timer that fires every 200 milliseconds to examine the position of the item being dragged every 200 milliseconds. If the item is within 100 pixels from the top or bottom edge of the control, the code scrolls the control. An MSDN Howto article (Q177743) describes this technique in detail. Listing 1 contains a few statements that determine whether to scroll the control’s items up or down and enables the Timer control, but the actual scrolling of the control takes place from within the Timer event handler.

When the user drops the item, the control fires the OLEDragDrop event. In this event’s handler (see Listing 2) you retrieve the item being dragged and place it under the highlighted node. Because you saved the item’s Key to a Data object passed to the event handler as argument, you can quickly retrieve the corresponding node by passing the key as argument to the Nodes collection. To move the original node under a new parent node, we simply set its ParentNode property to the selected node. By changing the node’s parent, in effect, we move it under a new parent. Changing the node’s parent also moves all subordinate nodes . The code also makes sure that the item can be dropped onto the selected node. For example, an item can’t be dropped on one of its child nodes, for example, because this would create a circular reference.

The code presented so far takes care of the run-time editing operations on the TreeView control. Examine the control’s KeyDown event handler to see how the control handles the other keystrokes. It’s very easy to manipulate the nodes of the control (add new nodes, delete existing ones and edit any node’s caption) with the keyboard. To change the hierarchy of a node, drag it with the mouse and drop it on its new parent node.Persisting the Nodes Collection
The TreeView control doesn’t provide a Save (neither a Load) method, so we’ll have to implement our own routines for persisting the control’s nodes. The simplest way to save a TreeView control’s Nodes collection is in XML format, because XML gives you intrinsic support for hierarchical structures. The sample code uses the MSXML component to create an XML document that contains the data and structure of the TreeView control’s nodes. VB6 doesn’t install MSXML by by default, but you can download it from MSDN and install it on your computer. The sample code uses MSXML version 3 (sp2), but you can use either version 3 or 4.

To use the MSXML component in your code, add a reference to the class to your project: open the Project menu, select References and on the References dialog box check the Microsoft XML v3.0 (or 4.0) component. This class provides all the methods you need to either create or read an XML document and process its nodes.

The Save Nodes button on the main form creates a “flat” XML document: each node is saved as a separate element and the node’s properties (the node’s caption, key and the parent node’s key) are saved as attributes of the element. In other words, this version stores the hierarchical structure as relationships inherent in the ParentKey node attributes. The code creates a XML element for each Node object in the TreeView’s Nodes collection. Each element has four attributes: Caption, Key, Tag and ParentKey. The resulting document looks like this:

The ParentKey attribute is the ID of the parent node, so you can reconstruct the node hierarchy later. Listing 3 shows the code behind the Save button. The code creates the root element and then iterates through the control’s nodes with a For…Next loop. Each iteration creates a new element, retrieves the values of its attributes from the current node’s properties and then adds the element under the root element.

A Better XML Structure

The XML document generated by the Save Nodes button is a valid XML document and it contains all the information we need to reconstruct the original Nodes collection on the control. However, it doesn’t reflect the hierarchical structure of the collection. Take a look at the following XML document, which nests the nodes under their parent nodes. Here’s an excerpt of of the document:

                                                                                
Figure 2. Viewing the persisted XML file in Internet Explorer after saving the Treeview with the nodes shown on in Figure 1.

Notice how this representation nests country nodes within continent nodes and city nodes within country nodes, clearly reflecting the structure of the control’s Nodes collection. While this representation doesn’t provide any programmatic advantages over the “flat” version, it’s much easier for humans to read. . As you will shortly see, the routine that reads the XML nodes and populates the TreeView control is the same, no matter how you choose to structure the XML file.

The code behind the Save Nodes (Nested) button loops through the root nodes of the TreeView control adding each node to the XML document’s root element and then calls the AddChildNodes subroutine to add the current node’s child nodes. Listing 4 shows this code.

The AddChildNodes() subroutine does all the work and is surprisingly simple. Like most recursive routines, the AddChildNodes() subroutine is both short and efficient. It creates a element for the current node and writes it to the XML document. It doesn’t close the element immediately; instead, it loops through any child nodes of the current node, calling itself recursively for each child node, and closes the initial element only after storing all the child nodes. Listing 5 shows the AddChildNodes() subroutine.

Reading Back the Persisted Nodes
No matter which XML format you prefer, the code for reading the XML file and populating the TreeView control with the persisted nodes is the same, thanks to the functionality of the DOMDocument class. The Click event code for the Load Nodes button starts by creating a DOMDocument object and loading the XML file created by one of the Save buttons (you can change the code to prompt the user to select the file to be loaded). After loading the file successfully, the code iterates through its nodes with the GetElementsByTagName method, extracts each node’s Caption, Key and ParentKey attribute values, and adds a new item to the TreeView control, setting its properties to the attribute values contained in the XML element. (See Listing 6

You retrieve each element in the XML document using the following statement:

Then the code calls the GetAttribute method of the newElement variable to retrieve the ParentKey, Key and Caption attributes, recreate the node and place it on the control. Each node automatically appears under its parent node (as long as the parent nodes are added to the control before their child nodes), because the code sets the ParentKey property to the proper parent when it creates the node.

As you’ve seen, extending the TreeView control to support editing, dragging and dropping nodes, and persistance isn’t particularly difficult. Adding these features lets you use the native TreeView control where you might otherwise need to use a custom control.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist