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.
Share the Post:
As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.
When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.
Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job