Monday, May 26, 2008

How to Iterate TreeView Nodes Recursively

Level: Intermediate
Knowledge Required:
  • Recursion
  • TreeView Control

In this article we will use a code which Recursively Iterates through each TreeView Node.

Private Sub IterateTreeViewNodesRecursively(Optional ByRef ParentNode As TreeNode = Nothing)
Dim objNodes As TreeNodeCollection

' if parentnode is NOT given then use treeview's nodes
If ParentNode Is Nothing Then
objNodes = Me.TreeView1.Nodes
Else ' else it means parentnode is mentioned so use it's nodes
objNodes = ParentNode.Nodes
End If

For Each n As TreeNode In objNodes
' perform your checking here
'If n.Checked Then
' ' perform your operation here
'End If
'If n.Tag = "FOLDER" Then
' ' perform your operation here
'End If

If n.Nodes.Count > 0 Then ' if this node has children
' iterate each children
Call IterateTreeViewNodesRecursively(n)
End If
End Sub

Note that if you want to access the checked nodes only you can use the above code but I have discussed another approach in the earlier post you can also see it.

No comments: