简体   繁体   中英

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) { }

    }

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("'", "''"));

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)
        {

        }

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