首页 > 代码库 > C#-WinForm-三级联动
C#-WinForm-三级联动
三级联动 - 查询地区,选择省份自动显示该省份的市、区县
有如下一个数据库
一、写查询方法
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("0001"); 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"; }
完成地区选择
C#-WinForm-三级联动
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。