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

时间:2022-06-02 17:21:29

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
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#程序设计有所帮助。