前台界面:
后台代码:
namespace _04省市联动
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int r = 0;
private void Form1_Load(object sender, EventArgs e)
{
r = 1;
//所有省份显示到第一个下拉框中
LoadAreaByAreaPId(0);
}
private void LoadAreaByAreaPId(int v)
{
List<Area> list=new List<Area>();
list.Add(new Area() {AreaId = -1,AreaName = "---请选择---"});
string sql = "select AreaId,AreaName from TblArea where AreaPId="+v;
using (SqlDataReader reader=SqlHelper.ExecuteDataReader(sql))
{
if (reader.HasRows)
{
while (reader.Read())
{
Area a=new Area();
a.AreaId = Convert.ToInt32(reader["AreaId"]);
a.AreaName = reader["AreaName"].ToString();
list.Add(a);
}
}
}
if (r==1)
{
cbPro.DataSource = list;
cbPro.DisplayMember = "AreaName";
cbPro.ValueMember = "AreaId";
}
if(r==2)
{
cbCity.DataSource = list;
cbCity.DisplayMember = "AreaName";
}
}
private void cbPro_SelectedIndexChanged(object sender, EventArgs e)
{
#region 练习用的代码
//if (cbPro.SelectedIndex != 0)
//{
// cbCity.Items.Clear();
// //获取当前省份的id
// int id = Convert.ToInt32(cbPro.SelectedValue);
// string sql = "select AreaId,AreaName from TblArea where AreaPId=" + id;
// //List<Area> list = new List<Area>();
// using (SqlDataReader reader = SqlHelper.ExecuteDataReader(sql))
// {
// if (reader.HasRows)
// {
// while (reader.Read())
// {
// Area a = new Area();
// a.AreaId = Convert.ToInt32(reader["AreaId"]);
// a.AreaName = reader["AreaName"].ToString();
// cbCity.Items.Add(a); //重写了Area类的ToString()方法 public override string ToString()
//否则添加的是类的命名空间 {
return this.AreaName;
}
// }
// }
// }
//}
#endregion
#region 简化写法,使用r变量判断事件
r = 2;
if (cbPro.SelectedIndex != 0)
{
int id = Convert.ToInt32(cbPro.SelectedValue);
LoadAreaByAreaPId(id);
}
#endregion
}
}
}