C#递归加载树

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using System.Data.SqlClient;
11 using _01NPOI的写入;
12 
13 namespace TreeViewTest
14 {
15     public partial class Form1 : Form
16     {
17         public Form1()
18         {
19             InitializeComponent();
20         }
21 
22         private void Form1_Load(object sender, EventArgs e)
23         {
24             //窗体加载的时候把数据加载到TreeView中
25             LoadData(treeView1.Nodes, 0);
26         }
27         private void LoadData(TreeNodeCollection tvCollection,int p)
28         {
29             //1、获取pid数据
30             DataTable dt = GetAreasByAreaPid(p);
31             //2、遍历数据并加载到TreeView上
32             foreach (DataRow dr in dt.Rows)
33             {
34                 int areaId =Convert.ToInt32(dr[0]);
35                 string areaName = dr[1].ToString();
36                 TreeNode tvNode = tvCollection.Add(areaName);
37                 tvNode.Tag = areaId;
38                 LoadData(tvNode.Nodes, areaId); //递归
39             }
40         }
41         //根据父ID获取所有子元素
42         private DataTable GetAreasByAreaPid(int pid)
43         {
44             string strSql = "SELECT AreaId,AreaName FROM TblArea WHERE TblArea.AreaPid=@pid";
45             SqlParameter[] pama = new SqlParameter[] { new SqlParameter("@pid", SqlDbType.Int) { Value = pid } };
46             return sqlHelper.ExecuteDataTable(strSql, CommandType.Text, pama);
47         }
48     }
49 }
 1         public static DataTable ExecuteDataTable(string strSql, CommandType cmdType, params SqlParameter[] pms)
 2         {
 3             DataTable dt = new DataTable();
 4             SqlConnection conn = new SqlConnection(conStr);
 5             SqlDataAdapter adap = new SqlDataAdapter(strSql, conn);
 6             try
 7             {
 8                 adap.SelectCommand.CommandType = cmdType;
 9                 if (pms != null)
10                 {
11                     adap.SelectCommand.Parameters.AddRange(pms);
12                 }
13                 adap.Fill(dt);
14                 return dt;
15             }
16             catch (Exception EX)
17             {
18                 MessageBox.Show(EX.Message.ToString());
19             }
20             finally
21             {
22                 conn.Close();
23                 conn.Dispose();
24                 adap.Dispose();
25             }
26             return dt;
27         }
28     }
类库

链接:https://pan.baidu.com/s/1gfSaD6Ej50OjcayBiH1kjw
提取码:u05h

posted @ 2019-05-14 18:13  陈彦斌  阅读(600)  评论(0)    收藏  举报