我的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
问题是这个循环深度是定义的,我只是把节点淹没了三个层次.如果下次用户选择父节点,有七个级别?
使用递归
原文链接:https://www.f2er.com/vb/255697.htmlFunction 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