我试过这段代码:
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)时,它会起作用
当我将它们组合在一起时(就像我编写的代码一样),它会引发stackoverflow异常。 该代码在树形视图中用于复选框。
编辑:已解决 请访问此链接TreeView.BeforeCheck Event寻求帮助(仔细阅读)
答案 0 :(得分:2)
如果您尝试单步执行代码,您会看到每次尝试检查/取消选中某个节点时,都会重新输入该事件。
尝试添加此项检查:
If e.Action = TreeViewAction.Unknown Then
Exit Sub
End If
如果您没有手动点击(编辑:也适用于按键选择)节点将退出事件并停止无限循环
答案 1 :(得分:0)
我认为你正在寻找你可以尝试....
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