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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27017057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 18:30:07  来源:igfitidea点击:

How to find the all parent node of a child node from bottom to top in tree view control using vb.net

vb.nettreeview

提问by Piyush

Here i have below Treeview as shown in image.

如图所示,我在下面的 Treeview 中有。

treeview

树视图

for child node G gi want to fetch all the parent nodes name from bottom to top and store into list. means in list should add G g, F f, D d, B b.

对于子节点,G g我想从底部到顶部获取所有父节点名称并存储到列表中。表示列表中应添加 G g, F f, D d, B b。

please suggest the solution.

请提出解决方案。

thanks in advance...

提前致谢...

采纳答案by Piyush

I have created one function for it which will add all the parent in the list until parent is not nothing for the selected node.

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

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

回答by Harval

This code will help you to obtain information about the parents node.

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

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

回答by LarsTech

If you just need the list of text of the parent nodes, you can simply use the FullPath property of the selected node:

如果您只需要父节点的文本列表,您可以简单地使用所选节点的 FullPath 属性:

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

If you need the list of nodes, just keep checking the parent until it's nothing:

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

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