How to get a list of all child nodes in a TreeView in .NET

后端 未结 10 1111
抹茶落季
抹茶落季 2020-12-15 21:28

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 use

10条回答
  •  被撕碎了的回忆
    2020-12-15 21:38

    If someone still wants to do the recursion approach, using Jop's code, and keeping the TreeNodes (so you can use their .tag, .name, .checked or .text properties) here is my version

    Public Shared Function GetChildren(objTree As TreeView) As List(Of TreeNode)
        Dim nodes As List(Of TreeNode) = New List(Of TreeNode)
        For Each parentNode As TreeNode In objTree.Nodes
            nodes.Add(parentNode)
            GetAllChildren(parentNode, nodes)
        Next
    
        Return nodes
    End Function
    
    Public Shared Sub GetAllChildren(parentNode As TreeNode, nodes As List(Of TreeNode))
        For Each childNode As TreeNode In parentNode.Nodes
            nodes.Add(childNode)
            GetAllChildren(childNode, nodes)
        Next
    End Sub
    

提交回复
热议问题