Select a TreeView node from code

stewarts

Newcomer
Joined
Apr 8, 2003
Messages
22
Please help!!! I have a TreeView something like this:

Numbers
---Range 1-3
-------1
-------2
-------3
---Range 4-6
-------4
-------5
-------6

How can I select the node that reads "1" from my VB .NET code? I know you have to use the SelectedNode property, but I can't figure out how to code it and can't find an example anywhere. Thanks!!!
 
I don't know how to code the TreeView.SelectedNode property. I have a reference manual that says "To select a node from code, just assign the TreeNode object to the tree view's SelectedNode property." Does anyone have a example how the code would look? I'm new to VB .NET and am struggling.
 
You first need to decide on how you want to search for the applicable node. If its via the node's text property, then do something like this:
Visual Basic:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'look for a node with a text property value of 'Node3'
        TreeView1.SelectedNode = GetNode("Node3", TreeView1.Nodes)
'ensure the focus set on the node
        TreeView1.Select()
End Sub

Private Function GetNode(ByVal text As String, ByVal parentCollection As TreeNodeCollection) As TreeNode

        Dim ret As TreeNode
        Dim child As TreeNode

        For Each child In parentCollection 'step through the parentcollection
            If child.Text = text Then
                ret = child
            ElseIf child.GetNodeCount(False) > 0 Then ' if there is child items then call this function recursively
                ret = GetNode(text, child.Nodes)
            End If

            If Not ret Is Nothing Then Exit For 'if something was found, exit out of the for loop

        Next

        Return ret

End Function
You can also use the tag property of each node to store a key when you populate the treeview. You can then replace the text search with your key search.

Cheers!
 
Back
Top