将新的子节点添加到特定的父节点

时间:2015-01-05 21:18:13

标签: vb.net visual-studio-2012

我正在尝试将新的子节点添加到特定的父节点中。

问题是我找不到可用于指定我想要使用哪个父节点的属性 只有我可以使用的是:

 TreeView1.SelectedNode.Nodes.Add(newNode)  

但我不想使用SelectedNode

我需要的应该是这样的:

TreeView1.ParentNode(Me.ds_Tables.Table.Rows(a).Item(0)).Nodes.Add(newNode)  

修改
所以,我写了一个ParentNode,只是为了清楚说明这是一个我要添加新节点的节点 节点和数据表之间的关系是我使用表列结果为Node命名。

问题是我的表看起来像(id, code, name, parentIdparentId是该表的id列。因此,当填充parentId(而不是Null)时,这意味着该结果是该表的另一个结果的一部分。 (我希望你能清楚,如果不是我会尝试以不同的方式解释)。

所以,基本上我必须找到填充parentId的所有结果,找到哪个结果拥有它并将该名称放入“父节点”。

1 个答案:

答案 0 :(得分:2)

选项1

您似乎在某个时刻同时读取了所有数据,然后构建了树。如果是这种情况,您可以在将TreeNodes添加到TreeView之前完全构造它们:

Dim items As New List(Of Item)()
Dim map As New Dictionary(Of Integer, TreeNode)()

' first, create all TreeNode objects
For Each item As var In items
    Dim node As New TreeNode()
    ' set node values
    map.Add(item.Id, node)
Next

' second, construct the relations
For Each item As var In items
    Dim node = map(item.Id)
    If item.ParendID.HasValue Then
        map(item.ParentID).Nodes.Add(node)
    Else ' no parent = root node
        TreeView.Nodes.Add(node)
    End If
Next

选项2

如果您的树是动态的,您仍然可以保留一个全球字典,指明哪些Id链接到TreeNode

Private map As New Dictionary(Of Integer, TreeNode)();

选项3

使用Tag属性并为TreeNodeCollection编写扩展方法:

<System.Runtime.CompilerServices.Extension> _
Public Shared Function Find(nodes As TreeNodeCollection, item As Object) As TreeNode
    For Each node As var In nodes
        If node.Tag IsNot Nothing AndAlso node.Tag.Equals(item) Then
            Return node
        End If
    Next
    Return Nothing ' or throw an exception
End Function

然后使用

TreeView.Nodes.Find(parentID).AddNodes(...)