简体   繁体   中英

Search or filter data in datagridview using C#

I have problem with my code, when I search data and then data is fit with my datagridview, my program runs without error. But when I search data with wrong data, there is an error. This is my code:

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;
}

The error always occurs in my bindingsourse:

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();
    }
}

Try this :

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;
           }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM