Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleLoad a TreeView control from an XML file in VB .NET
DescriptionThis example shows how to load a TreeView control from an XML file in Visual Basic .NET.
KeywordsTreeView, XML
CategoriesControls, Files and Directories, VB.NET
 
Subroutine LoadTreeViewFromXmlFile loads the XML document, clears the TreeView control's nodes, and calls subroutine AddTreeViewChildNodes, passing it the TreeView's Nodes collection and the XML document's root node.
 
' Load a TreeView control from an XML file.
Private Sub LoadTreeViewFromXmlFile(ByVal file_name As _
    String, ByVal trv As TreeView)
    ' Load the XML document.
    Dim xml_doc As New XmlDocument
    xml_doc.Load(file_name)

    ' Add the root node's children to the TreeView.
    trv.Nodes.Clear()
    AddTreeViewChildNodes(trv.Nodes, _
        xml_doc.DocumentElement)
End Sub
 
Subroutine AddTreeViewChildNodes takes as parameters a TreeNodeCollection that should contain the child nodes defined by an XML node. For each of the XML node's children, the subroutine adds a new TreeView node to the node collection. It then calls itself recursively to add children to the new child node.
 
' Add the children of this XML node 
' to this child nodes collection.
Private Sub AddTreeViewChildNodes(ByVal parent_nodes As _
    TreeNodeCollection, ByVal xml_node As XmlNode)
    For Each child_node As XmlNode In xml_node.ChildNodes
        ' Make the new TreeView node.
        Dim new_node As TreeNode = _
            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 Then _
            new_node.EnsureVisible()
    Next child_node
End Sub
 
For more information about using XML in Visual Basic .NET, see my book Visual Basic .NET and XML.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated