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:
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 United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will
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,
A major security breach recently occurred at a well-known company, leading to unauthorized access to sensitive customer data. Sources within the organization have confirmed that
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
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
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.
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,
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
A major security breach recently occurred at a well-known company, leading to unauthorized access to sensitive customer data. Sources within the organization have confirmed that the technology team is diligently
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
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.
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
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
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
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
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