How to traverse a treeview

Treeview traversal and recursion

In Rest Results Explorer i showed how to Create a treeview from json using the treeView control. Objects like the treeview are generally dealt with recursively - see Getting started with recursion and Getting to Grips with recursion for more detail on this simple yet elusive technique. Here I will show how to traverse a treeview in just a few lines of code.

Example

This example will use the treeview implemented in Rest Results Explorer , and select or unselect branches of data returned by a tweetsentiment query to the Rest Results Explorer. In the example, i have checked trends (and need all children to be checked), but have unchecked description, and similarily I would expect the children of description to become unchecked. 



Code

All that is required is to deal with the nodeCheck event, and pass through the state of the checked box to each of the nodes' children, which recursively call their children to pass on the status of the parents' check box. This is all there is to it.


Private Sub trcJobject_NodeCheck(ByVal node As MSComctlLib.node)
    ' if we get here then a check has been set on on or off..
    ' all the children need to inherit this
    grantParentNodeCheck node, node.Checked
End Sub
Private Sub grantParentNodeCheck(parent As MSComctlLib.node, _
                        Optional check As Boolean = True)
    Dim child As MSComctlLib.node
    parent.Checked = check
    Set child = parent.child
    While Not child Is Nothing
        grantParentNodeCheck child, check
        Set child = child.Next
    Wend
End Sub

Summary

Now take a look at some more complex recursion topics in Getting to Grips with recursion.  In the meantime why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available.

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.







Comments