树视图节点的子节点

时间:2012-05-15 18:06:35

标签: asp.net xml vb.net

我有一个xml文件,结构如下:

<table name="tblcats">
    <row>
        <Id>3680</Id>
        <Industry>Associations</Industry>
        <ParentId>1810</ParentId>
    </row>
    <row>
        <Id>1592</Id>
        <Industry>Fortune 100</Industry>
        <ParentId>1810</ParentId>
    </row>
    <row>
        <Id>1601</Id>
        <Industry>Oil &amp; Gas Operations</Industry>
        <ParentId>1689</ParentId>
    </row>
    <row>
</table>

我想使用此XML文件创建树视图。我写了以下代码

   ' 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()
        trv.Nodes.Add(New TreeNode(xml_doc.DocumentElement.Name))
        AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement)
    End Sub

    ' 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 = New TreeNode(child_node.Item("Industry").InnerText, child_node.Item("Id").InnerText)

            parent_nodes.Add(new_node)

        Next child_node
    End Sub

但它会创建一个这样的树视图:

->table
->Associations
->Fortune 100

我希望表格像这样的父元素

->table
  ->Associations
  ->Fortune 100

这样,如果我单击表节点,则所有树都会折叠或展开。请建议我如何解决它

1 个答案:

答案 0 :(得分:0)

问题是您将树视图控件本身传递给AddTreeViewChildNodes方法,因此它将在同一顶层添加所有节点。您需要将您创建的根节点传递给方法,以便在其下添加子节点。

变化:

    trv.Nodes.Add(New TreeNode(xml_doc.DocumentElement.Name))
    AddTreeViewChildNodes(trv.Nodes, xml_doc.DocumentElement)

要:

    Dim rootNode As TreeNode = New TreeNode(xml_doc.DocumentElement.Name)
    trv.Nodes.Add(rootNode)
    AddTreeViewChildNodes(rootNode, xml_doc.DocumentElement)