Tech Technology Tech Technology - 4 months ago 6x Question

check parent when all its nodes are checked and check all nodes when their parent is checked throws error

I have tried this code:

Private Sub TreeView1_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterCheck
Dim blnUncheck As Boolean = False
Dim tn As TreeNode
If e.Node.Nodes.Count = 0 Then
For Each child As TreeNode In e.Node.Parent.Nodes
If child.Checked = False Then
blnUncheck = True
End If
If blnUncheck = False Then
e.Node.Parent.Checked = True
e.Node.Parent.Checked = False
End If (the code above is used to check parent when nodes are checked)
Else (the code below is used to check nodes of parent when parent is checked)
If e.Node.Checked = True Then
For Each tn In e.Node.Nodes
tn.Checked = True
For Each tn In e.Node.Nodes
tn.Checked = False
End If
End If
End Sub

in order to: a) check all nodes when their parent is checked
b) check parent when all it's nodes are checked

Although when when I remove one of two(a,b) from the code it works

When I combine them(as the code I have written), it throws a stackoverflow exception.
The code is used in treeview with checkboxes.

Visit this linkTreeView.BeforeCheck Event for help (read carefully)


If you try and step through your code you will see that every time you try and check/uncheck a node, you reenter the event.

Try adding this check:

If e.Action = TreeViewAction.Unknown Then
    Exit Sub
End If

If you havent manually clicked (EDIT: Also works for selecting by keypress) the node it will exit the event and stop the infinite loop