C#递归加载树
2021-01-21 13:13
标签:ext ram type 元素 name system val 数据 new C#递归加载树 标签:ext ram type 元素 name system val 数据 new 原文地址:https://www.cnblogs.com/ljs-13/p/12109198.html 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 }
上一篇:C# 递归产生树