根据省份选择城市的功能(连接数据库的)

根据http://blog.csdn.net/huangzhe10/archive/2010/08/18/5819802.aspx建立两个表,分别为省份表tb_province,城市表tb_city。

如上图所示布局,左侧ComboBox显示省份列表,右侧ComboBox显示城市列表

双击form的空白处首先把省份的列表加载到ComboBox里来

方法一:

using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;AttachDBFilename=|DataDirectory|/country.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from tb_province"; using (SqlDataReader reader = cmd.ExecuteReader()) { cmbprovince.Items.Clear(); while (reader.Read()) { string db_provincename = reader.GetString(reader.GetOrdinal("name")); cmbprovince.Items.Add(db_provincename); cmbprovince.SelectedIndex = 0;//默认显示第一个省份 } } }  

方法二:

先增加应用程序配置文件,其代码如下:

 

程序自启动加载省份列表代码:

string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from tb_province"; using(SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { tb_province item = new tb_province(); item.id = reader.GetInt32(reader.GetOrdinal("id")); item.name = reader.GetString(reader.GetOrdinal("name")); cmbprovince.Items.Add(item); cmbprovince.SelectedIndex = 0;//默认第一个省份 } } }   

双击省份的ComboBox写其当值改变时的代码:

方法一:

string pname = (string)cmbprovince.SelectedItem;//获取选择的省份名称 using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;AttachDBFilename=|DataDirectory|/country.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select id from tb_province where name=@ne";//根据省份名称选择此省份的id cmd.Parameters.AddWithValue("ne", pname); int pid = Convert.ToInt32(cmd.ExecuteScalar()); cmd.Dispose(); SqlCommand citycmd = conn.CreateCommand(); citycmd.CommandText = "select name from tb_city where provinceid=@provinceid";//根据省份的id=城市表中的provinceid,过滤出此省份下的所有城市名 citycmd.Parameters.AddWithValue("provinceid",pid); using (SqlDataReader reader = citycmd.ExecuteReader()) { cmbcity.Items.Clear(); while (reader.Read()) { string cname = reader.GetString(reader.GetOrdinal("name")); cmbcity.Items.Add(cname); } cmbcity.SelectedIndex = 0;//默认显示第一个城市 } }  

方法二:

string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString; tb_province item=(tb_province)cmbprovince.SelectedItem; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "select * from tb_city where provinceid=@pid"; cmd.Parameters.Add(new SqlParameter("pid",item.id)); using (SqlDataReader reader = cmd.ExecuteReader()) { cmbcity.Items.Clear(); while (reader.Read()) { string city_name = reader.GetString(reader.GetOrdinal("name")); cmbcity.Items.Add(city_name); cmbcity.SelectedIndex = 0;//默认选定省份的第一个城市 } } }

你可能感兴趣的:(c#)