如何获得在.NET中一个TreeView所有子节点的列表 [英] How to get a list of all child nodes in a TreeView in .NET
问题描述
我在具有多个层次有子节点更多的子节点,没有定义深度的所有子的WinForms .NET应用程序中的TreeView控件。当用户(根级不一定)选择任何父节点,我怎么能得到beneith的父节点?
I have a TreeView control in my WinForms .NET application that has multiple levels of childnodes that have childnodes with more childnodes, with no defined depth. When a user selects any parent node (not necessarily at the root level), how can I get a list of all the nodes beneith that parent node?
例如,我开始了这一点:
For example, I started off with this:
Dim nodes As List(Of String)
For Each childNodeLevel1 As TreeNode In parentNode.Nodes
For Each childNodeLevel2 As TreeNode In childNodeLevel1.Nodes
For Each childNodeLevel3 As TreeNode In childNodeLevel2.Nodes
nodes.Add(childNodeLevel3.Text)
Next
Next
Next
现在的问题是,这个循环深度定义,我只得到安葬节点向下三个层次。如果下一次用户选择一个父节点是什么,有七个级别?
The problem is that this loop depth is defined and I'm only getting nodes burried down three levels. What if next time the user selects a parent node, there are seven levels?
推荐答案
使用递归
Function GetChildren(parentNode as TreeNode) as List(Of String)
Dim nodes as List(Of String) = New List(Of String)
GetAllChildren(parentNode, nodes)
return nodes
End Function
Sub GetAllChildren(parentNode as TreeNode, nodes as List(Of String))
For Each childNode as TreeNode in parentNode.Nodes
nodes.Add(childNode.Text)
GetAllChildren(childNode, nodes)
Next
End Sub
这篇关于如何获得在.NET中一个TreeView所有子节点的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!