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:
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:
Implement Keystroke Handlers 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:
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:
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.
The editing operations themselves are straightforward and completely keyboard-driven.Implementing Node Drag-and-Drop
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:
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 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 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 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:
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 Reading Back the Persisted Nodes You retrieve each 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. About Our Editorial ProcessAt 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 JournalistCharlie Frank Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience. View Author Ai boosts weather forecasting amid climate crisis Cameron Wiggins September 19, 2024 3:42 PM Ellison announces end to Oracle passwords Johannah Lopez September 19, 2024 3:41 PM What Are Key Factors in Successfully Launching a Startup? featured September 19, 2024 3:32 PM Cybersecurity market rebounds with AI growth Johannah Lopez September 19, 2024 1:15 PM Evolution impacts ecosystem tipping point dynamics April Isaacs September 19, 2024 11:09 AM What Are Effective Methods for Handling Large Data Sets? featured September 19, 2024 10:45 AM UK foreign secretary calls for climate reset Rashan Dixon September 19, 2024 8:04 AM How Can You Ensure Code Quality During Rapid Development Cycles? featured September 19, 2024 6:56 AM How To Video Call On Android Johannah Lopez September 18, 2024 11:34 PM How To Leave Group Text On Android Johannah Lopez September 18, 2024 11:34 PM Amazon improves delivery with generative AI Rashan Dixon September 18, 2024 5:36 PM How AI is Shaping the Future of Student Learning Kyle Lewis September 18, 2024 3:24 PM A Comprehensive Guide to Choose the Right Residential SOCKS5 Proxies Rashan Dixon September 18, 2024 2:57 PM Google integrates AI content into Search Noah Nguyen September 18, 2024 1:33 PM What Are Strategies for Scaling a Tech Business Quickly? featured September 18, 2024 11:54 AM How AI deepfakes amplify the deep doubt era April Isaacs September 18, 2024 11:33 AM Ai experts warn of catastrophic risks Cameron Wiggins September 18, 2024 8:11 AM How Can You Improve App Performance for a Better User Experience? featured September 18, 2024 7:54 AM What Are Tips for Optimizing Cloud Infrastructure Costs? featured September 18, 2024 4:25 AM How To Transfer Apps From Android To Android Johannah Lopez September 17, 2024 10:36 PM How To Connect Apple Watch To Android Without iPhone Johannah Lopez September 17, 2024 10:36 PM Apple Intelligence debuts with iOS 18.1 Grace Phillips September 17, 2024 3:40 PM Founder Mode Vs. Manager Mode – The New Debate Editorial Staff September 17, 2024 1:39 PM This New Adventure Game is Charming as it is Puzzling Editorial Staff September 17, 2024 1:34 PM Apple AirPods Pro 2 approved by FDA Noah Nguyen September 17, 2024 1:30 PM |