SoFunction
Updated on 2025-03-01

C# TreeView unlimited directory tree implementation method

This article describes the implementation method of C# TreeView infinite directory tree. Share it for your reference, as follows:

#region binds to the customer treeprotected void bindTreeView()
{
  ();
  string userid = Session["UserID"].ToString();
  string sqlwr = new SY_ADMINUSER().GetUserIDListByLoginUser(userid, "CUSTOMERSERVICE", false);
  DataTable dt = ("Select PARENTID,CUSTOMERID,CUSTOMERSHORT,CUSTOMERSERVICE from CU_CUSTOMER where ISDELETE='0' " + sqlwr + " order by CUSTOMERSHORT ").Tables[0];
  //Define temporary tree node  TreeNode tmpNd;
  //Special treatment  foreach (DataRow dr in )
  {
    DataRow[] drs = ("CUSTOMERID='" + dr["PARENTID"] + "'");
    if ( == 0) //No superior node    {
      dr["PARENTID"] = "0";
    }
  }
  ();
  //Get the array formed by DataRow with parent node null from DataTable  DataRow[] rows = ("PARENTID='0'");
  //Transfer the root node array  foreach (DataRow row in rows)
  {
    tmpNd = new TreeNode();
    // Assign value to the root node     = row["CUSTOMERID"].ToString();
     = row["CUSTOMERSHORT"].ToString();
     = true;
    //Add nodes into the tree    (tmpNd);
    AddTree(dt, TreeView1, tmpNd, row["CUSTOMERID"].ToString());
  }
}
public void AddTree(DataTable dt, TreeView tv, TreeNode pNode, string CUSTOMERID)
{
  DataRow[] rows = ("PARENTID='" + CUSTOMERID + "'");
  TreeNode tmpNd;
  foreach (DataRow row in rows)
  {
    tmpNd = new TreeNode();
    // Assign value to the root node     = row["CUSTOMERID"].ToString();
     = row["CUSTOMERSHORT"].ToString();
     = true;
    (tmpNd);
    //Add nodes into the tree    //(pNode);
    AddTree(dt, TreeView1, tmpNd, row["CUSTOMERID"].ToString());
  }
}
#endregion

For more information about C#, please visit the special topic of this site:Summary of thread usage techniques for C# programming》、《Summary of C# operation skills》、《Summary of XML file operation skills in C#》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

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