I have a treeview where each node has a "ID" field along with a few other... how could I start at the root of the tree and search for the node with "ID" and return the node?
Printable View
I have a treeview where each node has a "ID" field along with a few other... how could I start at the root of the tree and search for the node with "ID" and return the node?
Hey pal, This will search the TreeView recursively and will return the first "TreeNode" that has a "Text" property equal to "myNodeId". I don't understand what you mean about subclassing so I write it this way to run easily. If you Inherited a class from "TreeNode" class and added a property called "ID" to it, It's ok, just change every "TreeNode" to "myInheritedTreeNode" and change the "myNode.Text = myNodeId" in "SearchNodesRecursive" to "myNode.ID = myNodeId". To search for different IDs, change the value of myNodeId.
Good Luck.Code:Private Const myNodeId As String = "AnID"
Private Sub myButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles myButton.Click
Dim tmpNode As System.Windows.Forms.TreeNode
tmpNode = SearchTreeView(myTreeView)
If (tmpNode Is Nothing) = False Then
'Do something
End If
End Sub
Public Function SearchTreeView(ByVal myTreeView As System.Windows.Forms.TreeView) As System.Windows.Forms.TreeNode
Dim i As Integer
Dim tmpNode As System.Windows.Forms.TreeNode
For i = 0 To (myTreeView.Nodes.Count - 1)
tmpNode = SearchNodesRecursive(myTreeView.Nodes(i))
If (tmpNode Is Nothing) = False Then
Return tmpNode
End If
Next i
Return Nothing
End Function
Public Function SearchNodesRecursive(ByVal myNode As System.Windows.Forms.TreeNode) As System.Windows.Forms.TreeNode
If (myNode Is Nothing) = False Then
If myNode.Text = myNodeId Then
Return myNode
Else
If myNode.Nodes.Count > 0 Then
Dim i As Integer
Dim tmpNode As System.Windows.Forms.TreeNode
For i = 0 To (myNode.Nodes.Count - 1)
tmpNode = SearchNodesRecursive(myNode.Nodes(i))
If (tmpNode Is Nothing) = False Then
Return tmpNode
End If
Next i
End If
Return Nothing
End If
Else
Return Nothing
End If
End Function
1. Declare a module level variable for you Treeview class
Private objNode As clsMyTreeNode
2.Declare a module level variable for a treeNode object
eg dim myNode as treeNode
3. In the Treeview_AfterSelect event
objNode = CType(e.Node, clsMyTreeNode)
You can now access all properties of the treenode including your subclassed properties
eg, if you you have an additional property called ID you can access this property by m_ANID = objNode.ID, if you have declared a variable m_ANID to hold this value.