C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#中TreeView适合两级节点的选中节点方法

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#程序设计有所帮助。

您可能感兴趣的文章:
阅读全文