C#中TreeView完成合適兩級節點的選中節點辦法。本站提示廣大學習愛好者:(C#中TreeView完成合適兩級節點的選中節點辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C#中TreeView完成合適兩級節點的選中節點辦法正文
本文實例講述了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#法式設計有所贊助。