[VB.NET] Recursive search through a treeview
I'm bad with recursing, but pretty good with cursing. :)
Here's what I came up with to recurse through a treeview, given an ID value for a node, and to return it's NodeIndex property.
VB Code:
Public Function FindAndReturnNodeIndex(ByRef tnc As TreeNodeCollection, ByVal strID As String) As String
Dim tnRec As TreeNode
Dim strTemp As String
Dim tnRet As TreeNode
For Each tnTemp As TreeNode In tnc
If tnTemp.ID = strID Then
Return tnTemp.GetNodeIndex
Exit Function
End If
Next
For Each tnRec In tnc
tnRet = SearchChildNodes(tnRec, strID)
If Not tnRet Is Nothing Then
Return tnRet.GetNodeIndex
End If
Next
End Function
Public Function SearchChildNodes(ByRef tn As TreeNode, ByVal strID As String) As TreeNode
Dim tnTemp As TreeNode
Dim tnRec As TreeNode
For Each tnTemp In tn.Nodes
If tnTemp.ID = strID Then
Return tnTemp
Else
If (tnTemp.Nodes.Count > 0) Then
tnRec = SearchChildNodes(tnTemp, strID)
If Not tnRec Is Nothing Then
Return tnRec
End If
End If
End If
Next
End Function
Call it like so:
VB Code:
Dim asdfy As String = FindAndReturnNodeIndex(Me.tvFamilyTree.Nodes, "TimeCard2")
Although I'll be submitting it to the codebank, anyone see any scope for improvements?
Re: [VB.NET] Recursive search through a treeview
I don't use .Net quite yet (or Treeviews), so I can't be 100% sure I haven't missed something...
Just two comments:
shouldn't tnTemp be defined in FindAndReturnNodeIndex?
does Return perform an Exit Function? If not, you should use the Exit throughout (else remove it from the one place it is).
Your recursion looks fine to me, you do the important job of "escaping" the routine if there are no nodes, or a match is found.
Re: [VB.NET] Recursive search through a treeview
I've declared tnTemp in the line:
VB Code:
For Each tnTemp As TreeNode In tnc
And the rest seems fine from what you say, so thanks. :)