Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter datagridview using a textbox in C#?

I tired to filter a datagridview using a textbox, the textbox is contained in a tabpage, but it is not working, here is the code :

    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = "like '%" + textBox1.Text.Trim() + "%' ";
        }
        catch (Exception) { }

    }
like image 268
amer Avatar asked Aug 09 '11 12:08

amer


2 Answers

RowFilter allows you to specify a filter based on column values. So the LIKE applies to a specific column, not to the whole row. So your condition should be

"YourColumn like '%" + textBox1.Text.Trim() + "%'

Also, don't forget that the TextBox could contain the ' character, so you need to escape it:

"YourColumn like '%" + textBox1.Text.Trim().Replace("'", "''") + "%'

Or, cleaner:

string.Format("YourColumn like '%{0}%'", textBox1.Text.Trim().Replace("'", "''"));
like image 121
Thomas Levesque Avatar answered Sep 19 '22 18:09

Thomas Levesque


try this it is searching for the letter no matter where is that letter ( beginning, mid, or at the end)

    private void TextBox1_TextChanged(object sender, EventArgs e)
    {
        try
        {
            //this code is used to search Name on the basis of TextBox1.text
            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format("Column_Name like '%{0}%'", TextBox1.Text.Trim().Replace("'", "''"));
        }
        catch (Exception) 
        {

        }
    }

This one searching from the first letter with following the next one by one.

try
        {
            ((DataTable)dataGridViewX1.DataSource).DefaultView.RowFilter = "Column_Name like'" + textBox1.Text.Trim().Replace("'", "''") + "%'";
        }
        catch (Exception)
        {

        }
like image 32
Many Mar Avatar answered Sep 22 '22 18:09

Many Mar