递归实现treeView下的省市联动
namespace 省市联动_递归_ { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { CreateTreeNode(0,treeView1.Nodes); } private List<Model> GetAreaNameById(int id) { List<Model> ls = new List<Model>(); string sql = "select * from TblArea where AreaPId=@id"; SqlParameter sp1 = new SqlParameter("@id", SqlDbType.Int) { Value = id }; using (SqlDataReader reader = SqlHelp.ExecuteReader(sql, sp1)) { if (reader.HasRows) { while (reader.Read()) { int AreaId = reader.GetInt32(0); string AreaName = reader.GetString(1); int AreaPId = reader.GetInt32(2); ls.Add(new Model(AreaId,AreaName,AreaPId)); } } } return ls; } private void CreateTreeNode(int id, TreeNodeCollection tnc) { List<Model> ls= GetAreaNameById(id); foreach (Model item in ls ) { TreeNode tn= tnc.Add(item.AreaName); tn.Tag = item.AreaId; CreateTreeNode(item.AreaId, tn.Nodes); } } } }
namespace 省市联动_递归_ { class Model { public int AreaId { set; get; } public string AreaName { set; get; } public int AreaPId { set; get; } public Model(int areaId,string areaName,int areaPId) { this.AreaId=areaId; this.AreaName = areaName; this.AreaPId = areaPId; } }
sqlhelp
namespace 省市联动_递归_ { public static class SqlHelp { static readonly string constr = ConfigurationManager.ConnectionStrings["MyconnectionString1"].ConnectionString; public static int ExecuteNoneQuery(string sql,params SqlParameter[] p) { using (SqlConnection conn=new SqlConnection(constr) ) { using (SqlCommand cmd=new SqlCommand(sql,conn)) { if (p!=null) { cmd.Parameters.AddRange(p); } if (conn.State==ConnectionState.Closed) { conn.Open(); } return cmd.ExecuteNonQuery(); } } } public static int ExecuteScalar(string sql, params SqlParameter[] p) { using (SqlConnection conn=new SqlConnection(constr)) { using (SqlCommand cmd=new SqlCommand(sql,conn)) { if (p!=null) { cmd.Parameters.AddRange(p); } if (conn.State==ConnectionState.Closed) { conn.Open(); } return (int)cmd.ExecuteScalar(); } } } public static SqlDataReader ExecuteReader(string sql,params SqlParameter[] p) { SqlConnection conn=new SqlConnection(constr); using(SqlCommand cmd=new SqlCommand(sql,conn)) { if (p!=null) { cmd.Parameters.AddRange(p); } try { conn.Open(); return cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection); } catch (Exception) { conn.Close(); conn.Dispose(); throw; } } } } }
我叫小小菜,想要成为一棵大大包心菜.