数据库绑定dataGridView查询保证标题名称不变

前面在vs2008连接Acess数据库中讲过如何绑定dataGridView,这里不再复述

 

用这种方法判断一下

  if (myDataReader.HasRows)
            {
                BindingSource bs = new BindingSource();
                bs.DataSource = myDataReader;
                dataGridView1.DataSource = bs;

            }
            else
            {
                dataGridView1.Rows.Clear();
            }

2.      public int OleCreateConnection2(string cmdstr)//使用ExecuteScalar查询返回int类型
        {
            int count=0;
            string myConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Documents and Settings\\Administrator\\桌面\\new.mdb";
            mycon = new OleDbConnection(myConnectionString);
            try
            {
                mycon.Open();
                myCommand = new OleDbCommand(cmdstr, mycon);
                count = int.Parse(myCommand.ExecuteScalar().ToString());//它的返回值为Object类型,可以转化成int类型
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            return count;
        }

 

3.模糊查询

           string cmdstr = "select * from T_Student where id like ? and name like ? ";

            OleCreateConnection(cmdstr);

            if (myDataReader.HasRows)
            {
                BindingSource bs = new BindingSource();
                bs.DataSource = myDataReader;
                dataGridView1.DataSource = bs;

            }
            else
            {
                dataGridView1.Rows.Clear();
            }
            myDataReader.Close();

            string cmdstr2 = "select count(*) from T_Student where id like ? and name like ? ";
            myCommand2 = new OleDbCommand(cmdstr2, mycon);
            /
            myCommand2.Parameters.Clear();//清空参数
           
            OleDbParameter pid2 = new OleDbParameter("cs1", OleDbType.Char);//设置第一个参数
            pid2.Value = "%" + textBox1.Text + "%";
            myCommand2.Parameters.Add(pid2);


            OleDbParameter pname2 = new OleDbParameter("cs2", OleDbType.Char);//设置第一个参数
            pname2.Value = "%" + textBox2.Text + "%";
            myCommand2.Parameters.Add(pname2);

            int count =(int)( myCommand2.ExecuteScalar());//这边是执行数据库操作
            label3.Text = "共检索到" + count + "条记录";


            mycon.Close();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值