欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-30 10:18:46
本文实例讲述了c#中treeview实现适合两级节点的选中节点方法。分享给大家供大家参考。具体如下: class treeviewchecked { bo...

本文实例讲述了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#程序设计有所帮助。