Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Visual Basic
Expertise: Beginner
Aug 8, 1997



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Sequential Navigation of a TreeView Control

While the TreeView control with its associated Node objects is a far cry better than the VB3 Outline control, it lacks a method for sequentially traversing the tree, as if you were scrolling using the up and down arrow keys. The For Each construct allows you to process every node, but in order of Index, which can be meaningless if the tree is sorted by the display text. This code, to be called after the TreeView has been loaded and sorted, creates a 1-based array of keys in the order that the Nodes appear in a TreeView:

Global asKey() as String

Sub Main()
        '...Fill the TreeView1 control
        ReDim asKey(1 To _
                TreeView1.Nodes.Count) As String
        KeyArray TreeView1.Nodes(1).Root.FirstSibling, 1
End Sub

Private Sub KeyArray(n as Node, _
        Optional iStart)
        Static i As Integer
        If IsMissing(iStart) Then
                i = i + 1
                i = iStart
        End If
        asKey(i) = n.Key

        If n.Children > 0 Then KeyArray _
        Do While n <> n.LastSibling
                i = i + 1
                Set n = n.Next
                asKey(i) = n.Key
                If n.Children > 0 Then _
                        KeyArray n.Child
End Sub

The first sibling of the root of an arbitrary node is used to return the first entry in the TreeView. The use of the Optional parameter allows the routine to be called whenever the TreeView is reloaded or modified. Once the array is established, it allows for sequential navigation or searching, or whatever operation would benefit from knowing the order of all Nodes.

Greg Frizzle
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date