Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Treeview Nodes 3

Status
Not open for further replies.

Ladyhawk

Programmer
Jan 22, 2002
534
AU
What's the best way to iterate through all of the nodes (including kids) in a treeview?

I tried For each node in tvwX.nodes but that only goes through the top level. I tried for i = 0 to tvx.getnodecount - 1, but I don't think the indexes of the nodes are sequential.

Please help!

Ladyhawk. [idea]
** ASP/VB/Java Programmer **
 
Because each node has it's own node collection, you need a recursive function to iterate through all nodes. The following code searches for a node with 'Hello' in the tag:

Public Function FindNode(ByVal n As TreeNode, ByVal NodeTagToFind As String) As TreeNode

If n.Tag.ToString = NodeTagToFind Then Return n

Dim tn As TreeNode

For Each tn In n.Nodes

Dim newnode As TreeNode

newnode = FindNode(tn, NodeTagToFind)

If Not newnode Is Nothing Then Return newnode

Next

You can then call it using:

Dim tn as TreeNode = FindNode(TreeView1.Nodes(0), "Hello")

When finding a node, it is always easiest to start at the very first node (TreeView.Nodes(0)) so that the function iterates through every node collection. However, if your tree view is very large you may need to check how long the recursive function takes to find the required node (in my experience, this method of finding nodes is pretty quick).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top