Select TreeNode using Fullpath (of node)
Hello
I have a treeview that is populated. The user will have some node selected in that treeview. A refresh function is called, and the program remembers the full path, so that after the treeview is cleared and repopulated, the same user selected node can be reselected for them automatically.
I have the full path of a tree node. If the full path is "nodea\nodeb\nodec" how can I automatically select that node using code?
Thank you!
Re: Select TreeNode using Fullpath (of node)
In VB6 each Node in Treeview has a key value. With this key you can find node very quickly.
AFAIK and I could be wrong but since VB.NET treeview control doesn't have this property, it seems you need to make a recursive subroutine to find the node you are searching for...
Re: Select TreeNode using Fullpath (of node)
Re: Select TreeNode using Fullpath (of node)
I was hoping there was some way to select the node directly using the path that I couldn't find.
Something like
TreeView1.SelectedNode=TreeView.NodeFromPath("nodea\nodeb\nodec")
And I already have the tags chuck full of data pertaining to the node, so I cant use those.
I guess a sub routine would work, but I'm dealing with 10,000+ nodes and the quicker the better.
Re: Select TreeNode using Fullpath (of node)
There is no method provided, but you can easily construct one of your own.
Try this:
Add this to a module
vb.net Code:
Imports System.Runtime.CompilerServices
Module MyTreeViewExtensions
<Extension()> _
Public Function AddTreeNode(ByVal parentNode As TreeNode, ByVal text As String) As TreeNode
Dim tn As New TreeNode(text)
tn.Name = parentNode.Name & parentNode.TreeView.PathSeparator & text
parentNode.Nodes.Add(tn)
Return tn
End Function
<Extension()> _
Public Function AddTreeNode(ByVal treeView As TreeView, ByVal text As String) As TreeNode
Dim tn As New TreeNode(text)
tn.Name = text
treeView.Nodes.Add(tn)
Return tn
End Function
<Extension()> _
Public Function NodeFromPath(ByVal treeView As TreeView, ByVal path As String) As TreeNode
Dim tn As TreeNode = treeView.Nodes.Find(path, True).First()
Return tn
End Function
End Module
Now use these methods to add new nodes and to search for nodes.
e.g.
vb.net Code:
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'' adding tree nodes
TreeView2.AddTreeNode("nodea")
TreeView2.Nodes(0).AddTreeNode("nodeb")
TreeView2.Nodes(0).Nodes(0).AddTreeNode("nodec")
'' searching for node by path demo
TreeView2.SelectedNode = TreeView2.NodeFromPath("nodea\nodeb\nodec")
TreeView2.ExpandAll()
TreeView2.Select()
End Sub
Of course I haven't put any error handling code for simplicity of understanding. You should put appropriate error handlers. e.g. if no node is found with the path you specified etc.