Treenode- find node (using resursive method)  
Author Message
Andrew Shearer





PostPosted: Visual Basic Express Edition, Treenode- find node (using resursive method) Top

i wanted to find a given node in my treeview which could be at any level...... as my unique identifier is a custom group and key combiniation (which i store in the tag property as a custom object) i could not use the built-in .Find() method as this is based on the key only.

so i wrote the following method (which works). Is this the beast way to write a recursive function to traverse the tree

Private Function RecursiveGetnode(ByVal nodes As TreeNodeCollection, ByVal eTreeViewgroup As TreeGroup, ByVal iKey As Integer) As TreeNode

Dim nFoundNode As TreeNode

'
nFoundNode = Nothing

For Each n As TreeNode In nodes

'determine match
With CType(n.Tag, TreeViewTag)
If .Group = eTreeViewgroup AndAlso .Key = iKey Then
nFoundNode = n
Return nFoundNode
Else
nFoundNode = RecursiveGetnode(n.Nodes, eTreeViewgroup, iKey)

If Not nFoundNode Is Nothing Then
Return nFoundNode
End If
End If

End With

Next

End Function



Visual Studio Express Editions34  
 
 
nobugz





PostPosted: Visual Basic Express Edition, Treenode- find node (using resursive method) Top

Looks good to me. You could speed it up just a bit if you set the key for a node to a unique value so you can use n.Items("key"). That won't work with your own iKey though unless you modify your Nodes.Add() method call. Something like:
TreeView1.Nodes.Add("K" + CStr(iKey), text)