Treeview Search

rockronie

Member
Joined
Aug 8, 2006
Messages
12
Programming Experience
Beginner
how to search for a particular TreeNode in a TreeView. The search can start at any node..

Thanks in advance
 
Here is a sub I made for you. The code below searchs in all parentNodes and you have the option to specify if you want to look at child nodes or not (code will run faster if you do not search in childNodes).

Note: The below code goes as deep as ONE level of child nodes.

VB.NET:
    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

Usage:
VB.NET:
findinTreeNode("WhatYouWantToFind", True)
If you do not want to include childNodes then set the bool to false.
VB.NET:
findinTreeNode("WhatYouWantToFind", [B]False[/B])
 
Last edited:
To search any level child nodes collection you have to do standard recursive method, meaning the method calls itself intil a match or no more elements to search. aBsOlUts code will only go as deep as first child. Example:
VB.NET:
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
You could enter the search string in a textbox and call the method from a button, example:
VB.NET:
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
 
Back
Top