資料庫繫結dataGridView查詢保證標題名稱不變

wzm10455發表於2013-05-03

前面在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();

 

相關文章