两个ComboBox的内容关联

 在用户注册或者是查询时通常都会用到两个下拉框的关联操作。当在一个下拉框中选择安徽,另个下拉框立即出现安徽的城市。选择江苏,则江苏的城市会出现。其实这个也就是数据库的绑定问题。好了,废话不说了。首先要设计数据库,这个问题就不用我说了吧。要弄好省和城市的关联。从数据库中把数据提取出来我也不说了,现在把省和城市的数据分别放到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);

当选择其中一个省份的时候就会触发一个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);
     
        }

行了,原理很简单,操作起来其实也很简单。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值