c#生成无限级目录树

时间:2022-04-24 12:03:02

TreeView tvFile = new TreeView();
  /// <SUMMARY>
  /// 创建根基目录,比如:XX的权限设置
  /// </SUMMARY>
  public void MakeRoot()
  {

   this.tvFile.Nodes.Clear();
   this.tvFile.ShowPlus = true;
   TreeNode root = new TreeNode();
   root.Text = "根基目录";
   root.NodeData = "";
   root.CheckBox = true;
   root.Expanded = true;
   this.tvFile.Nodes.Add(root);
   
   AddFatherTree(root);  
  }

  /// <SUMMARY>
  /// 从数据库中导入父节点
  /// </SUMMARY>
  /// <PARAM name="SuperNode"></PARAM>
  public void AddFatherTree(TreeNode SuperNode)
  {
   ds = GetDataSet();

   string NodeDes="";
   string NodeID="";
   DataTable dt = ds.Tables[0];
   if(dt.Rows.Count &gt; 0)
   {
    foreach(DataRow dr in dt.Rows)
    {
     NodeDes = dr["NodeDes"].ToString();
     NodeID = dr["NodeID"].ToString();
     TreeNode FatherNode = new TreeNode();
     if(fatherID != "")
     {     
      FatherNode.Text = NodeDes;
      FatherNode.ID = NodeID;
      FatherNode.CheckBox = true;
      FatherNode.Expanded = true;
     
      SuperNode.Nodes.Add(FatherNode);     
     }
    
     AddChildTree(FatherNode, ID);
    }
   }
  }

  /// <SUMMARY>
  /// 导入子节点
  /// </SUMMARY>
  /// <PARAM name="SuperNode"></PARAM>
  /// <PARAM name="strFatherID"></PARAM>
  public void AddChildTree(TreeNode SuperNode, string strFatherID)
  {
   DataSet ds = GetDataSet();
   string NodeDes="";
   string NodeID="";
   DataTable dt = ds.Tables[0];

   foreach(DataRow dr in dt.Rows)
   {
    NodeDes = dr["NodeDes"].ToString();
    NodeID = dr["NodeID"].ToString();

    TreeNode ChildNode = new TreeNode();
    ChildNode.Text = NodeDes;
    ChildNode.ID = NodeID;
    ChildNode.CheckBox = true;
    ChildNode.Expanded = true;

    SuperNode.Nodes.Add(ChildNode);
   
    AddChildTree(ChildNode,NodeID);   
   }  
  }