在用户注册或者是查询时通常都会用到两个下拉框的关联操作。当在一个下拉框中选择安徽,另个下拉框立即出现安徽的城市。选择江苏,则江苏的城市会出现。其实这个也就是数据库的绑定问题。好了,废话不说了。首先要设计数据库,这个问题就不用我说了吧。要弄好省和城市的关联。从数据库中把数据提取出来我也不说了,现在把省和城市的数据分别放到dataset类型的ds1和ds2中。
首先:在构造函数中写一个方法把省份填充进去。
string
[] usergroup
=
new
string
[ds1.Tables[
0
].Rows.Count];
for ( int i = 0 ; i < ds.Tables[ 0 ].Rows.Count; i ++ )
{
usergroup[i] = ds.Tables[ 0 ].Rows[i][ 0 ].ToString();
}
this .comboBox1.Items.AddRange(usergroup);
for ( int i = 0 ; i < ds.Tables[ 0 ].Rows.Count; i ++ )
{
usergroup[i] = ds.Tables[ 0 ].Rows[i][ 0 ].ToString();
}
this .comboBox1.Items.AddRange(usergroup);
当选择其中一个省份的时候就会触发一个comboBox1_SelectedIndexChanged事件,然后从数据库中把相应的城市提取出来,在绑定到ComboBox2中就可以了。
private
void
comboBox1_SelectedIndexChanged(
object
sender, EventArgs e)
{
this .comboBox2.Items.Clear();
int index = this .comboBox1.SelectedIndex;
string strconn = " server=(local); " + " integrated security=SSPI; " + " database=Student; " ;
SqlConnection conn = new SqlConnection(strconn);
SqlDataAdapter da = new SqlDataAdapter( " select city from city where ShengID=1+ " + index, conn);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
// comboBox1.DataSource = ds.Tables[0];
string [] usergroup = new string [ds.Tables[ 0 ].Rows.Count];
for ( int i = 0 ; i < ds.Tables[ 0 ].Rows.Count; i ++ )
{
usergroup[i] = ds.Tables[ 0 ].Rows[i][ 0 ].ToString();
}
this .comboBox2.Text = usergroup[ 0 ];
this .comboBox2.Items.AddRange(usergroup);
}
{
this .comboBox2.Items.Clear();
int index = this .comboBox1.SelectedIndex;
string strconn = " server=(local); " + " integrated security=SSPI; " + " database=Student; " ;
SqlConnection conn = new SqlConnection(strconn);
SqlDataAdapter da = new SqlDataAdapter( " select city from city where ShengID=1+ " + index, conn);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
// comboBox1.DataSource = ds.Tables[0];
string [] usergroup = new string [ds.Tables[ 0 ].Rows.Count];
for ( int i = 0 ; i < ds.Tables[ 0 ].Rows.Count; i ++ )
{
usergroup[i] = ds.Tables[ 0 ].Rows[i][ 0 ].ToString();
}
this .comboBox2.Text = usergroup[ 0 ];
this .comboBox2.Items.AddRange(usergroup);
}
行了,原理很简单,操作起来其实也很简单。