Browse DevX
Sign up for e-mail newsletters from DevX


Making the Most of the VB TreeView Control : Page 5

Add run-time editing, drag-and-drop features and persistence to the TreeView control.

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 <NODE> 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.

Evangelos Petroutsos is a long time VB developer. When he's not writing code, he writes programming books and articles. His most recent title is Mastering Visual Basic .NET, published by Sybex. Reach him by e-mail at pevangelos@yahoo.com
Thanks for your registration, follow us on our social networks to keep up-to-date