C#中TreeView实现适合两级节点的选中节点方法

时间:2021-05-20

本文实例讲述了C#中TreeView实现适合两级节点的选中节点方法。分享给大家供大家参考。具体如下:

class TreeViewChecked{ bool isfirst = true; public TreeViewChecked(TreeView treeView) { treeView.AfterCheck += new TreeViewEventHandler(treeView_AfterCheck); treeView.AfterSelect += new TreeViewEventHandler(treeView_AfterSelect); } /// <summary> /// 点击文字,选中checkbox /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void treeView_AfterSelect(object sender, TreeViewEventArgs e) { if (e.Node.Checked) e.Node.Checked = false; else e.Node.Checked = true; if (isfirst) { isfirst = false; e.Node.TreeView.Nodes[0].Checked = false; } } /// <summary> /// 选中子节点,勾选父节点,选中父节点,勾选子节点 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void treeView_AfterCheck(object sender, TreeViewEventArgs e) { CheckTreeNode(e.Node); } /// <summary> /// 选中子节点,勾选父节点,选中父节点,勾选子节点 /// </summary> /// <param name="node"></param> private void CheckTreeNode(TreeNode node) { node.TreeView.AfterCheck -= new TreeViewEventHandler(treeView_AfterCheck); //如果不等于null,说明选择的是子节点 if (node.Parent != null) { TreeNode parent = node.Parent as TreeNode; //如果该节点是选中的 if (node.Checked) { //判断其父节点是否被选中,如果没有被选中则选中它 if (parent.Checked == false) { parent.Checked = true; } } else { bool ischecked = false; foreach (TreeNode child in parent.Nodes) { if (child.Checked) { ischecked = true; break; } } if (ischecked) parent.Checked = true; else parent.Checked = false; } }//如果等于null,说明选择的是根节点 else { foreach (TreeNode child in node.Nodes) { child.Checked = node.Checked; } } node.TreeView.AfterCheck += new TreeViewEventHandler(treeView_AfterCheck); }}

希望本文所述对大家的C#程序设计有所帮助。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章