Sub findinTreeNode(ByVal key As String, ByVal bIncludeChildNodes As Boolean)
'First look at all parent nodes...
For Each parentNode As TreeNode In TreeView1.Nodes
If parentNode.Text = key Then
MsgBox("Parent node found at " & parentNode.Index) 'Change to fit your needs
Exit For
End If
'Maybe what we are looking for belongs to a child node and the user has asked
'to look in childNodes.
If bIncludeChildNodes = True Then
For Each childNode As TreeNode In parentNode.Nodes
If childNode.Text = key Then
MsgBox("found at childNode with parent " & childNode.Parent.Text & " index is " & childNode.Index) 'Change to fit your needs
parentNode.Toggle()
Exit For
End If
Next
End If
Next
End Sub
findinTreeNode("WhatYouWantToFind", True)
findinTreeNode("WhatYouWantToFind", [B]False[/B])
Function searchTreeview(ByVal SearchString As String, ByVal Nodes As TreeNodeCollection, _
Optional ByVal ExactMatch As Boolean = False, _
Optional ByVal Recursive As Boolean = True) _
As TreeNode
Dim ret As TreeNode
For Each tn As TreeNode In Nodes
If ExactMatch = True Then
If tn.Text = SearchString Then Return tn
Else
If tn.Text.IndexOf(SearchString) <> -1 Then Return tn
End If
If Recursive = True Then
If tn.Nodes.Count > 0 Then
ret = searchTreeview(SearchString, tn.Nodes, ExactMatch, Recursive)
If Not ret Is Nothing Then Return ret
End If
End If
Next
Return Nothing
End Function
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles Button2.Click
Dim tn As TreeNode = searchTreeview(TextBox1.Text, TreeView1.Nodes, False, True)
If Not tn Is Nothing Then
TreeView1.SelectedNode = tn
Else
MsgBox("no match")
End If
End Sub