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.



Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.