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?
you need a recursive function to do this [or a loop equivalent, but the recursive version is simpler] - pseudocode:
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
Usually get a value at the specified node is interesting to programmers.This can be obtained as follows.Assumes that you have a TextBox control named texbox1 and a TreeView control named treeview1.Following would return the value of text at nodes level 0.
Adrian's method it's awesome. Works quite fast and worked better than the recursion approach. I've done a translation to VB. I've learned a lot from it. Hopefully someone still needs it.
To use it simply:
Here is the code, CHEERS! :
Thats it
Use recursion