日期:2014-05-20  浏览次数:20986 次

如何检索DataGridView中符合搜索条件的一行?
想请教各位大虾一下:
我用DataGridView成功返回显示了数据库的一张员工表(代码如下)
                private   void   BindEmployee()
                {
                        DataTable   employeeDataTable   =   Model.Employee.Employees.Instance.GetEmployees();//获取整张员工表
                        if   (employeeDataTable   !=   null)
                        {
                                this.dataGridView1.DataSource   =   employeeDataTable.Copy();//   bindingSource1;
                        }
                }
现在我想添加一个搜索功能,就是在一个对话框中输入员工的名字,然后符合条件的DataGridView里面相应的行就高亮度显示,请问这个功能大概要怎么实现呢?
(也就是如何去比较DataGridView里某一列的值呢?)

谢谢!!

------解决方案--------------------
比如对话框是一个listbox
for (int jj = 0; jj < dataGridView1.Rows.Count; jj++)
{
if (listBox1.Items[ii].ToString().Equals(dataGridViewqq.Rows[jj].Value.ToString()))
{
switch (dataGridView1.Rows[jj].Value.ToString())
{
case "张三 ":
...........
break;
case "李四 ":
...........
break;
}
}
}
------解决方案--------------------
对datagridview的数据源操作。把问题转化为查询DATATABLE。这样只需要foreach遍历一次就够了。
------解决方案--------------------
sorry,try..


private void DataBind()
{
OleDbConnection con = new OleDbConnection( "Provider=OraOLEDB.Oracle.1;data source=oracle;user id=butc;password=butc ");
OleDbDataAdapter sda = new OleDbDataAdapter( "select * from student ", con);
DataSet ds = new DataSet();
sda.Fill(ds, "student ");
this.dataGridView1.DataSource = ds.Tables[ "student "];
//只允许单行显示
this.dataGridView1.MultiSelect = false;
}

private void button2_Click(object sender, EventArgs e)
{
//遍历,由于绑定时,会自动在最后加上一空行,所以有效行数只是
//总行数-1
for (int i = 0; i < this.dataGridView1.Rows.Count - 1; i++)
{
if (this.dataGridView1.Rows[i].Cells[ "sname "].Value.ToString() == this.textBox2.Text.Trim())
{
//选中找到的行
this.dataGridView1.Rows[i].Selected = true;
return;
}
}
MessageBox.Show( "未找到 ");
}

private void Form1_Load(object sender, EventArgs e)
{
DataBind();