using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OperateExcel
{
public partial class 递归加载省市到treeView上 : Form
{
public 递归加载省市到treeView上()
{
InitializeComponent();
}
//动态加载
private void btnLoad_Click(object sender, EventArgs e)
{
treeView1.Nodes.Clear();
List<ProvinceEntity> list = GetListByPId(0);
LoadInfo(treeView1.Nodes, list);
}
private void LoadInfo(TreeNodeCollection treeNodeCollection, List<ProvinceEntity> list)
{
foreach (var item in list)
{
TreeNode node1=treeNodeCollection.Add(item.PName);
node1.Tag = item.Id;
List<ProvinceEntity> mlist = GetListByPId(item.Id);
LoadInfo(node1.Nodes, mlist);
}
}
public List<ProvinceEntity> GetListByPId(int pid)
{
List<ProvinceEntity> plist = new List<ProvinceEntity>();
string sql="select * from Base_Province where ParentId=@pid";
using (SqlDataReader reader = SqlHelper.ExecuteReader(sql, CommandType.Text, new SqlParameter("@pid", pid)))
{
if (reader.HasRows)
{
while (reader.Read())
{
ProvinceEntity pro = new ProvinceEntity();
pro.Id=reader.GetInt32(0);
pro.PName=reader.GetString(2);
pro.PId=reader.GetInt32(1);
plist.Add(pro);
}
}
}
return plist;
}
//动态删除
private void btnDelete_Click(object sender, EventArgs e)
{
if (this.treeView1.SelectedNode != null)
{
int areaId = (int)treeView1.SelectedNode.Tag;
DeleteNodeById(areaId);
treeView1.SelectedNode.Remove();
}
else
{
MessageBox.Show("请选择节点");
}
}
public void DeleteNodeById(int areaId)
{
List<ProvinceEntity> list = GetListByPId(areaId);
foreach (var item in list)
{
DeleteNodeById(item.Id);
}
string sql = "delete from Base_Province where Id=@id";
SqlHelper.ExecuteNoQuery(sql,CommandType.Text,new SqlParameter("@id",areaId));
}
}
}