private bool nextCheck(TreeNode n) //判断同级的节点是否全选 { foreach (TreeNode tn in n.Parent.Nodes) { if (tn.Checked == false) return false; } return true; } private bool nextNotCheck(TreeNode n) //判断同级的节点是否全不选 { if (n.Checked == true) { return false; } if (n.NextNode == null) { return true; } return this.nextNotCheck(n.NextNode); } private void cycleChild(TreeNode tn, bool check) //遍历节点下的子节点 { if (tn.Nodes.Count != 0) { foreach (TreeNode child in tn.Nodes) { child.Checked = check; if (child.Nodes.Count != 0) { cycleChild(child, check); } } } else return; } private void cycleParent(TreeNode tn, bool check) //遍历节点上的父节点 { if (tn.Parent != null) { if (nextCheck(tn)) { tn.Parent.Checked = true; } else { tn.Parent.Checked = false; } cycleParent(tn.Parent, check); } return; } // afterCheck private void treeView1_AfterCheak(object sender, TreeViewEventArgs e) //当选中或取消选中树节点上的复选框时发生 { //要求父节点被勾选,则子节点全部被勾选;父节点不被勾选,则子节点不全不被勾选 if (e.Node.Checked == true) { if (e.Action != TreeViewAction.Unknown) { cycleChild(e.Node, true); } if (e.Node.Parent != null) { if (nextCheck(e.Node)) { cycleParent(e.Node, true); } else { cycleParent(e.Node, false); } } } if (e.Node.Checked == false) { if (e.Action != TreeViewAction.Unknown) { cycleChild(e.Node, false); //中间节点不选中则子节点全部不选中 cycleParent(e.Node, false); //父节点不选中 } // bCheck = false; } return; }
最佳答案
0
直接用我这个得了:
Boolean bChildTrigger = true; Boolean bParentTrigger = true; private void tv_AfterCheck(object sender, TreeViewEventArgs e) { // MessageBox.Show("Node text: " + e.Node.Text); if (bChildTrigger) { CheckAllChildren(e.Node, e.Node.Checked); } if (bParentTrigger) { CheckMyParent(e.Node, e.Node.Checked); } } void CheckAllChildren(TreeNode tn, Boolean bCheck) { bParentTrigger = false; foreach (TreeNode ctn in tn.Nodes) { bChildTrigger = false; ctn.Checked = bCheck; bChildTrigger = true; CheckAllChildren(ctn, bCheck); } bParentTrigger = true; } void CheckMyParent(TreeNode tn, Boolean bCheck) { if (tn == null) return; if (tn.Parent == null) return; bChildTrigger = false; bParentTrigger = false; tn.Parent.Checked = bCheck; CheckMyParent(tn.Parent, bCheck); bParentTrigger = true; bChildTrigger = true; }
收获园豆:50
@一坨黄色: 不会吧。你自己改改试试。
@荒野的呼唤: 你的代码只要把tv_AfterCheak改成我的treeview控件名称就可以了撒..其它位置不用改撒.我试了不行啊..
其他回答(4)
0
private bool nextNotCheck(TreeNode n) //判断同级的节点是否全不选 { if (n.Checked == true) { return false; } if (n.NextNode == null) { return true; } return this.nextNotCheck(n.NextNode);
试了你的代码.不行啊,点父节点的check 下面的子节点没反应.