SoFunction
Updated on 2025-03-01

TreeView implements a selected node method suitable for two-level nodes in C#

This article describes the method of selecting nodes suitable for two-level nodes in C#. Share it for your reference. The details are as follows:

class TreeViewChecked
{
  bool isfirst = true;
  public TreeViewChecked(TreeView treeView)
  {
    += new TreeViewEventHandler(treeView_AfterCheck);
    += new TreeViewEventHandler(treeView_AfterSelect);
  }
  /// <summary>
  /// Click on the text and select checkbox  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  void treeView_AfterSelect(object sender, TreeViewEventArgs e)
  {
   if ()
     = false;
   else
     = true;
   if (isfirst)
   {
    isfirst = false;
    [0].Checked = false;
   }
  }
  /// <summary>
  /// Select the child node, check the parent node, select the parent node, check the child node  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  void treeView_AfterCheck(object sender, TreeViewEventArgs e)
  {
   CheckTreeNode();
  }
  /// <summary>
  /// Select the child node, check the parent node, select the parent node, check the child node  /// </summary>
  /// <param name="node"></param>
  private void CheckTreeNode(TreeNode node)
  {
    -= new TreeViewEventHandler(treeView_AfterCheck);
   //If it is not equal to null, it means that the child node is selected   if ( != null)
   {
    TreeNode parent =  as TreeNode;
    //If the node is selected    if ()
    {
     //Judge whether its parent node is selected, and if it is not selected, select it     if ( == false)
     {
       = true;
     }
    }
    else
    {
     bool ischecked = false;
     foreach (TreeNode child in )
     {
      if ()
      {
       ischecked = true;
       break;
      }
     }
     if (ischecked)
       = true;
     else
       = false;
    }
   }//If it is equal to null, it means that the root node is selected   else
   {
    foreach (TreeNode child in )
    {
      = ;
    }
   }
    += new TreeViewEventHandler(treeView_AfterCheck);
  }
}

I hope this article will be helpful to everyone's C# programming.