[RESOLVED] Find Treeview node and parent by Tag
I have a treeview which I put a bunch of Category Numbers in as the Tag of the node. Now after having that category number, in another application I wish to search the Category to get the parent text as well as the current selected text. My code looks like this thus far.
Code:
With TreeView1
For Each node As TreeNode In .Nodes
If node.Tag = TextBoxCategory.Text Then
.SelectedNode = node
tbLexicon.Text = .SelectedNode.Parent.Text & " > " & .SelectedNode.Text
Exit For
End If
Next
End With
This code came from MSDN, but it never finds my Tag which I know is in it as the other application supplies the values that I am sending back from the same treeview, just copied over to the other app. I have search for hours on this, but the results that I have tried just don't work or have errors that don't correct. For example... A sample of my treeview looks like this...
Air Condition and Heating
.........A/C Compressor & Clutch
..................Tag = 33543
.........A/C Hoses & Fittings
..................Tag = 33544
.........A/C & Heater Controls
..................Tag = 33545
Any help much appreciated.
Re: Find Treeview node and parent by Tag
This is what I use....
vb.net Code:
Dim gotNode As Boolean = False
Private Sub selectTreeNode(ByVal parentNode As TreeNode, ByVal nodeID As String)
If Not gotNode Then
For Each node As TreeNode In parentNode.Nodes
If node.Tag IsNot Nothing AndAlso node.Tag.ToString = nodeID Then
node.TreeView.SelectedNode = node
gotNode = True
Exit Sub
Else
Call selectTreeNode(node, nodeID)
End If
Next
End If
End Sub
and to use it....
vb.net Code:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
gotNode = False
For Each n As TreeNode In Me.TreeView1.Nodes
If Not gotNode Then
selectTreeNode(n, "This")
End If
Next
End Sub
I would not be at all surprised to see someone post a LINQ solution as well.
Re: Find Treeview node and parent by Tag
Thank you. It took me a minute to see what it was doing, but that worked great. Replaced "This" with TextBoxCategory.Text and filled tbLexicon by testing if gotNode was true.