Enumerate TreeView Nodes with a Recursive Procedure

This article first appeared in Visual Developer Magazine
(Note: This is my unedited original and may differ slightly from the published version.)
By Matt Hart

Recursive procedures are some of the most useful but difficult algorithms to program. Recursion is when a procedure calls itself with new data, usually stepping through levels of information before returning to a previous level. Stepping through all TreeView nodes and their children is easy when you use a recursive procedure.

In the TreeView’s NodeClick event, the currently selected Node is passed as a parameter. This is the starting point of the enumeration. If a Node has children, it gets a "plus" beside it. The result of the enumeration is displayed in a multi-line TextBox control.

Private Sub TreeView1_NodeClick(ByVal Node As ComctlLib.Node)
    Dim aNodes As String, lLevel As Long
    If Node.Children Then
        aNodes = "+" & Node.Text
    Else
        aNodes = Node.Text
    End If
    EnumChildren Node, aNodes, lLevel
    Text1.Text = aNodes
End Sub

The enumeration procedure increments the level when it begins and decrements the level when it ends. The level is used to correctly position the nodes for display. If a node has children, then the enumeration procedure is called with that node, otherwise the next child node is examined. The process continues until all nodes with children have been enumerated. The procedure executes very quickly.

Sub EnumChildren(N As Node, aNodes As String, lLevel As Long)
    lLevel = lLevel + 1
    Dim nC As Node
    If N.Children Then
        Set nC = N.Child
        Do
            If nC.Children Then
                aNodes = aNodes & vbCrLf & _
                         String$(lLevel, vbTab) & "+" & nC.Text
            Else
                aNodes = aNodes & vbCrLf & _
                         String$(lLevel, vbTab) & nC.Text
            End If
            EnumChildren nC, aNodes, lLevel
            If nC.Index = N.Child.LastSibling.Index Then Exit Do
            Set nC = nC.Next
        Loop
    End If
    lLevel = lLevel - 1
End Sub

Back to Articles
Copyright © 2000 by Matt E. Hart, All Rights Reserved Worldwide.
Nothing on this web site may be reproduced, in any form, without express written consent.