三级联动 - 查询地区,选择省份自动显示该省份的市、区县
有如下一个数据库
一、写查询方法
public class ChinaData
{
SqlConnection conn = null;
SqlCommand cmd = null; public ChinaData()
{
conn = new SqlConnection("server=.;database=mydb;user=sa;pwd=123");
cmd = conn.CreateCommand();
}
//查询方法 参数为父级代码
public List<China> Select(string pcode)
{
List<China> lc = new List<China>();
cmd.CommandText = "select *from ChinaStates where ParectAreaCode=@a";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@a",pcode);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while(dr.Read())
{
China c = new China();
c.AreaCode = dr["AreaCode"].ToString();
c.AreaName = dr["AreaName"].ToString();
c.ParentAreaCode = dr["ParentAreaCode"].ToString();
lc.Add(c);
}
}
conn.Close();
return lc;
}
}
查询方法
二、窗体启动时自动读取数据库数据
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//窗口打开时,自动查询代码0001中国下的子级数据
//绑定省
comboBox1.DataSource = new ChinaData().Select("");
comboBox1.DisplayMember = "AreaName";
comboBox1.ValueMember = "AreaCode";
//绑定市
comboBox2.DataSource = new ChinaData().Select(comboBox1.SelectedValue.ToString ());
comboBox2.DisplayMember = "AreaName";
comboBox2.ValueMember = "AreaCode";
//绑定区县
comboBox3.DataSource = new ChinaData().Select(comboBox2.SelectedValue.ToString());
comboBox3.DisplayMember = "AreaName";
comboBox3.ValueMember = "AreaCode";
}
}
窗体启动时自动读取数据库数据
三、实现改变选项的时候,展示子级内容
//省选中项改变时事件
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
//绑定市
comboBox2.DataSource = new ChinaData().Select(comboBox1.SelectedValue.ToString());
comboBox2.DisplayMember = "AreaName";
comboBox2.ValueMember = "AreaCode";
}
//市选中项改变时事件
private void comboBox2_SelectedIndexChanged_1(object sender, EventArgs e)
{
//绑定区县
comboBox3.DataSource = new ChinaData().Select(comboBox2.SelectedValue.ToString());
comboBox3.DisplayMember = "AreaName";
comboBox3.ValueMember = "AreaCode";
}
实现二级联动、三级联动
完成地区选择