如何使用vb.net在树视图控件中从下到上查找子节点的所有父节点

时间:2014-11-19 12:39:36

标签: vb.net treeview

这里我在Treeview下方,如图所示。

treeview

for child node G g我想从下到上获取所有父节点名称并存储到列表中。列表中的平均值应添加G g,F f,D d,B b。

请提出解决方案。

提前感谢...

3 个答案:

答案 0 :(得分:1)

我为它创建了一个函数,它将添加列表中的所有父函数,直到父对所选节点不是任何内容。

Public Function AllParents() As List(of String)
    Dim listOfNodeHierarchy As New List(Of String)
    listOfNodeHierarchy.Add(node.ToString)
    'If Child Node has parent, add the parent name of the Child node to the list
    While (node.Parent IsNot Nothing)
        listOfNodeHierarchy.Add(node.Parent)
        node = node.Parent
    End While
    return listOfNodeHierarchy
End Function

答案 1 :(得分:0)

此代码将帮助您获取有关父节点的信息。

dim selectedNode as treeNode = YourTreeViewSelectedNode   

dim nodePath as string= ""   'will store the full path 

'You get the full Path of the node like  'Parent\Child\GrandChild
'The Procedure will fill nodePath  

ObtainNodePath(selectedNode,nodePath)

msgbox(nodePath)



Private Sub ObtainNodePath(ByVal node As TreeNode, ByRef path As String)

    If node.Parent IsNot Nothing Then

        path = IO.Path.Combine(node.Text, path)    ' Parent\Child 

        If node.Parent.Level = 0 Then Exit Sub

        'Call again the method to check if can extract more info
        ObtainNodePath(node.Parent, path)

    End If

End Sub

答案 2 :(得分:0)

如果您只需要父节点的文本列表,则只需使用所选节点的FullPath属性:

For Each s As String In _
  TreeView1.SelectedNode.FullPath.Split(TreeView1.PathSeparator).Reverse

如果您需要节点列表,只需继续检查父节点,直到它没有:

Private Function ParentNodes(fromNode As TreeNode) As IEnumerable(Of TreeNode)
  Dim result As New List(Of TreeNode)
  While fromNode IsNot Nothing
    result.Add(fromNode)
    fromNode = fromNode.Parent
  End While
  Return result
End Function