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