根据ComboBox下拉的值查询数据库表中的内容并显示在DataGridView中

根据ComboBox下拉的值查询数据库表中的内容并显示在DataGridView中

1、在form窗体中添加一个ComboBox和一个DataGridView控件
2、编辑ComboBox的值
3、执行查询语句并将结果给DataGridView的DataSource
4、通过在ComboBox的SelectedIndexChanged事件就能做到查询并显示
代码如下:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            //txt得到下拉列表的值
            string txt = this.comboBox1.Text;
            sqlOpr sqlopr = new sqlOpr(); 
            //从数据库中fast查询对应的数据集ds放到bindingsource中
            DataSet ds = sqlopr.backds("fast", "select * from pass where leixing='"+ txt +"' order by keys asc");  
            
            if(ds == null)
            {
				return;
			}
               
            BindingSource bs = new BindingSource();
            bs.DataSource = ds.Tables[0];
            this.dataGridView1.DataSource = bs;
            
        }

封装的sqlOpr类的backds方法返回一个dataset数据集,代码如下:

 public DataSet backds(string sqlname, string sqloprstr)
        {
        	try
        	{
        		connstr = "server=" + server + ";uid=" + user + ";pwd=" + pwd + ";database=" + sqlname + "";
	            SqlConnection conn = new SqlConnection(connstr);
	            conn.Open();
	            SqlDataAdapter da = new SqlDataAdapter(sqloprstr, conn);
	            DataSet ds = new DataSet();
	            da.Fill(ds);
	            return ds;
	            //conn.Close();SqlDataAdapte有自动打开和关闭的功能
			}
			catch
			{
				return null
			}
        }
  • 3
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值