tags:

views:

104

answers:

1

How do I exit from the recursive loop from the code below. I would like to notify the end-user to select a checkbox in a msgBox before I exit the loop. Thanks.

Private Sub PrintRecursive(ByVal n As TreeNode)
    System.Diagnostics.Debug.WriteLine(n.Text)

    If (n.Checked = True) Then
        MessageBox.Show(n.Checked)
    Else
        If (n.Checked = False) Then
            MessageBox.Show("Check a bex")
        End If
        End If


        ' MessageBox.Show(n.Checked)
        Dim aNode As TreeNode
        For Each aNode In n.Nodes
            PrintRecursive(aNode)
        Next
End Sub

' Call the procedure using the top nodes of the treeview.
Private Sub CallRecursive(ByVal aTreeView As TreeView)
    Dim n As TreeNode
    For Each n In aTreeView.Nodes
        PrintRecursive(n)
    Next
End Sub
+1  A: 

One way would be to change PrintRecursive into a function that returns a boolean, for which true means "Stop"

Then change your recursion call to check the return value.

For Each aNode In n.Nodes
    if not PrintRecursive(aNode) then 
        msgbox("Notify User")
        return false
    end if
Next

A word of warning though, the messagebox will be displayed at each level of nesting when exiting the recursion. To avoid this you could add a parameter for the nesting level to PrintRecursive so you could tell when you were at the top level.

Private Function PrintRecursive(ByVal n As TreeNode, optional byval NestLevel as Integer=0) as Boolean
...
    For Each aNode In n.Nodes
        if not PrintRecursive(aNode,NestLevel+1) then 
            if (NestLevel=0) then msgbox("Notify User")
            return false
        end if
    Next
....
JohnFx
Hi John,I gave this code a try several times, but my compiler tells me at the <- If Not PrintRecursive(aNode, NestLevel + 1) Then -> part that the expression does not return a value. Is there something else I should look into? Also, do you think using this type of method is the best to loop through all nodes that are selected in a treenode? Thanks.
jpavlov
That was just an example of an approach, but in any case I made a few tweaks to the code. Also, did you change the method to a function?
JohnFx
Hi John, Thanks again for the coding support and the tips on being a better user on this site. I actually switched the sub-procedure over to a function, still running into a couple of problems but it doesn't seem that I am stuck in the recusive loop. My work is cut out for me this weekend. Thanks once again.
jpavlov
BTW. I took a look at your site. You have some really good stuff posted there.
jpavlov