使用C#在datagridview中搜索或过滤数据

时间:2014-11-28 19:07:58

标签: c# datagridview bindingsource

我的代码有问题,当我搜索数据然后数据适合我的datagridview时,我的程序运行没有错误。但是当我使用错误的数据搜索数据时,会出现错误。这是我的代码:

private void textBox6_TextChanged(object sender, EventArgs e)
{
    BindingSource bs = new BindingSource();
    bs.DataSource = dataGridView1.DataSource;
    bs.Filter = "EmployeeName like '*" + textBox6.Text + "*'";
    dataGridView1.DataSource = bs;
}

错误总是发生在我的绑定中:

private void bindingSource1_CurrentChanged(object sender, EventArgs e)
{
    DataTable dt = new DataTable();

    if (mode == 0)
    {
        DataRowView row = (DataRowView)bindingSource1.Current;
        textBox1.Text = row[0].ToString();
        textBox2.Text = row[1].ToString();
        textBox3.Text = row[2].ToString();

        if (row[3].Equals("Male"))
        {
            radioButton1.Checked = true;
            radioButton2.Checked = false;
        }
        else 
        {
            radioButton1.Checked = false;
            radioButton2.Checked = true; 
        }

        gender = row[3].ToString();
        textBox7.Text = row[4].ToString();
        richTextBox1.Text = row[5].ToString();
        textBox4.Text = row[6].ToString();
        textBox5.Text = row[7].ToString();
    }
}

1 个答案:

答案 0 :(得分:0)

  

试试这个:

private void textBox6_TextChanged(object sender, EventArgs e)
           {
            BindingSource bs = new BindingSource();
            bs.DataSource = dataGridView1.DataSource;
            bs.Filter = "EmployeeName like 'N" + textBox6.Text + "%'";
            dataGridView1.DataSource = bs;
           }