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; }
直接用我这个得了:
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; }
试了你的代码.不行啊,点父节点的check 下面的子节点没反应.
@一坨黄色: 不会吧。你自己改改试试。
@荒野的呼唤: 你的代码只要把tv_AfterCheak改成我的treeview控件名称就可以了撒..其它位置不用改撒.我试了不行啊..
private bool nextNotCheck(TreeNode n) //判断同级的节点是否全不选 { if (n.Checked == true) { return false; } if (n.NextNode == null) { return true; } return this.nextNotCheck(n.NextNode); }
这里这样写是有问题的,这里是递归调用,用return只是跳出了内层判断,改为break,然后在外层return
上面的代码实现不了"点击父节点,子节点全选" 是不是我的Cheak事件不对啊..哪位大侠帮看看.应该改哪里?上面的代码运行也没有哪里报错.
private void SetChild(TreeNode n,bool b){
n.Checked=b;
foreach (TreeNode cn in n.Nodes){
SetChild(cn,b);
}
}
private void treeView1_AfterCheak(object sender, TreeViewEventArgs e){
SetChild(e.Node,e.Node.Checked)
}
学习了,看得眼睛花了