C#-WinForm-三级联动
Posted 野性狼心
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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-三级联动的主要内容,如果未能解决你的问题,请参考以下文章