using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _07城市列表和递归Treeview
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//treevide.Nodes 就是根节点
//根节点.Nodes 就是子节点
LoadAreasToTree(0, treeView1.Nodes);
}
private void LoadAreasToTree(int pid, TreeNodeCollection nodes)
{
List<TblArea> list = GetAreaName(pid);//拿到所有pid对应的地名
foreach (TblArea item in list)
{
//创建一个根节点的变量,给递归使用
TreeNode node = nodes.Add(item.AreaName);//添加节点
node.Tag = item.AreaId;//对应的值
//递归子节点 刚刚添加的这个节点的节点node.Nodes
LoadAreasToTree(item.AreaId, node.Nodes);
//在方法内部的循环中调用方法自己,就是递归
}
}
private List<TblArea> GetAreaName(int pid)
{
string sql = " select [AreaName],[AreaId] from tblarea where areaPid=@pid";
SqlParameter pms = new SqlParameter("@pid", SqlDbType.Int) { Value = pid };
List<TblArea> list = new List<TblArea>();
using (SqlDataReader reader = SqlHelper.ExecuteReader(sql, pms))
{
if (reader.HasRows)
{
while (reader.Read())
{
TblArea model = new TblArea();
model.AreaName = reader.GetString(0);
model.AreaId = reader.GetInt32(1);
list.Add(model);
}
}
}
return list;
}
}
}
C#windowFrom控件,TreeView递归
最新推荐文章于 2022-07-17 01:27:24 发布