检查其所有节点时检查父节点,并在检查其父节点时检查所有节点抛出错误

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

我试过这个代码:

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
            Next
            If blnUncheck = False Then
                e.Node.Parent.Checked = True
            Else
                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
                        Next
                    Else
                        For Each tn In e.Node.Nodes
                            tn.Checked = False
                        Next
                    End If
        End If
    End Sub

为了:a) 在检查父节点时检查所有节点 b) 检查所有节点时检查父节点

虽然当我从代码中删除两个 (a,b) 之一时它起作用了

当我组合它们时(如我编写的代码),它会抛出一个 Whosebug 异常。 该代码在带有复选框的树视图中使用。

编辑:已解决 访问此linkTreeView.BeforeCheck Event寻求帮助(仔细阅读

如果您尝试单步执行代码,您会发现每次尝试 check/uncheck 一个节点时,您都​​会重新进入事件。

尝试添加此检查:

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

如果您没有手动单击(编辑:也适用于通过按键选择)节点,它将退出事件并停止无限循环

我想你正在找那个你可以试试....

Private Sub CheckAllChildNodes(treeNode As TreeNode, nodeChecked As Boolean)
    Dim node As TreeNode
    For Each node In treeNode.Nodes
        node.Checked = nodeChecked
        If node.Nodes.Count > 0 Then
            Me.CheckAllChildNodes(node, nodeChecked)
        End If
    Next node
End Sub


Private Sub node_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterCheck
    If e.Action <> TreeViewAction.Unknown Then
        If e.Node.Nodes.Count > 0 Then
            Me.CheckAllChildNodes(e.Node, e.Node.Checked)
        Else
            e.Node.Parent.Checked = True
        End If
    End If
End Sub