.netvb.nettreeviewtree-nodes

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


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?


Solution

  • Use recursion

    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