我的WinForms .NET应用程序中有一个TreeView控件,该控件具有多个级别的子节点,这些子节点的子节点具有更多的子节点,但未定义深度。当用户选择任何父节点(不一定在根级别)时,如何获取该父节点之间的所有节点的列表?
例如,我从以下开始:
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
问题在于,已定义了此循环深度,而我仅使节点埋入了三个层次。如果下次用户选择父节点时,有七个级别怎么办?
最佳答案
使用递归
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 - 如何在.NET中的TreeView中获取所有子节点的列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/177277/