运维开发网

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

运维开发网 https://www.qedev.com 2020-03-16 14:05 出处:网络 作者: 我心依旧
本文实例讲述了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#程序设计有所帮助。

0

精彩评论

暂无评论...
验证码 换一张
取 消