[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Load a TreeView control from an XML file in C#


This example shows how to load a TreeView control with XML data. An XML (eXtensible Markup Language) file is a simple file that stores tokens in a hierarchical manner. It doesn't do anything except hold data. Programs can load and manipulate the data. Because XML files hold hierarchical data, it makes sense to use them to hold data for a TreeView control, which displays hierarchical data.

The following LoadTreeViewFromXmlFile method starts the loading process.

// Load a TreeView control from an XML file. private void LoadTreeViewFromXmlFile(string filename, TreeView trv) { // Load the XML document. XmlDocument xml_doc = new XmlDocument(); xml_doc.Load(filename); // Add the root node's children to the TreeView. trv.Nodes.Clear(); AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement); }

This method loads the XML document, clears the TreeView control's nodes, and calls the following AddTreeViewChildNodes method to load the data, passing it the TreeView's Nodes collection and the XML document's root node.

// Add the children of this XML node // to this child nodes collection. private void AddTreeViewChildNodes( TreeNodeCollection parent_nodes, XmlNode xml_node) { foreach (XmlNode child_node in xml_node.ChildNodes) { // Make the new TreeView node. TreeNode new_node = parent_nodes.Add(child_node.Name); // Recursively make this node's descendants. AddTreeViewChildNodes(new_node.Nodes, child_node); // If this is a leaf node, make sure it's visible. if (new_node.Nodes.Count == 0) new_node.EnsureVisible(); } }

The AddTreeViewChildNodes method takes as parameters a TreeNodeCollection that should contain the child nodes defined by an XML node, and an XML node. For each of the node's children, the subroutine adds a new TreeNode to the node collection. The method then calls itself recursively to add the XML node's children to the new TreeNode.

When it finishes, the method calls the new node's EnsureVisible method to make sure it is expanded. It only calls EnsureVisible for leaf nodes (nodes without children). That will make the control expand all of the nodes leading to the leaf, so every node is visible. (You can omit this part if you prefer.)

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.