6

Here's my current code:

private void searchTextBox_TextChanged(object sender, EventArgs e)
    {
        (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", searchTextBox.Text);

    }

However my data grid table filters everything and becomes blank whenever I type something into the textbox. Any idea why? Thank you in advance!

huehuehue
  • 89
  • 1
  • 1
  • 3
  • are you sure that event is fired? – Nalaka Aug 04 '15 at 12:31
  • If you create a BindingSource to bind your DataTable to the DataGridView, you may use the "Filter" property of the BindingSource to filter the DGV without updating the DataSource(s) each time the filter condition changes. – Graffito Aug 04 '15 at 12:36
  • Please follow this stackoverflow answer [https://stackoverflow.com/a/54261346/4358971](https://stackoverflow.com/a/54261346/4358971) – Ritesh Kumar Jan 18 '19 at 21:05

4 Answers4

18

The likely reason you are seeing a blank DataGridView is due to your filter string searching for exact matches to the TextBox text.

"Name='{0}'"

Because you are updating this filter in the TextBox.TextChanged event, the first time you enter a character - no matches are found. For example, given the following grid:

╔════╦══════╗                    ╔════════╗
║ ID ║ Name ║      searchTextBox ║        ║
╠════╬══════╣                    ╚════════╝
║ 1  ║ Foo  ║
║ 2  ║ Bar  ║
║ 3  ║ Baz  ║
╚════╩══════╝

Entering Bar will give the following results:

╔════╦══════╗                    ╔════════╗
║ ID ║ Name ║      searchTextBox ║ B      ║
╠════╬══════╣                    ╚════════╝
╚════╩══════╝
╔════╦══════╗                    ╔════════╗
║ ID ║ Name ║      searchTextBox ║ Ba     ║
╠════╬══════╣                    ╚════════╝
╚════╩══════╝
╔════╦══════╗                    ╔════════╗
║ ID ║ Name ║      searchTextBox ║ Bar    ║
╠════╬══════╣                    ╚════════╝
║ 2  ║ Bar  ║
╚════╩══════╝

If this is the case, I've provided a few options below. If this is not the case, then you have a mystery.


  1. Exact matches: consider using the following event handler instead so that the filter is only applied once you've entered the full search text:

    private void searchTextBox_Leave(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(searchTextBox.Text))
        {
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Empty;
        }
        else
        {
            (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name='{0}'", searchTextBox.Text);
        }
    }
    
  2. StartsWith matches: for more fluid filtering on text changes:

    private void searchTextBox_TextChanged(object sender, EventArgs e)
    {
        (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '{0}%'", searchTextBox.Text);
    }
    
  3. Contains matches: again, fluid filtering:

    private void searchTextBox_TextChanged(object sender, EventArgs e)
    {
        (dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'", searchTextBox.Text);
    }
    
OhBeWise
  • 5,350
  • 3
  • 32
  • 60
  • Wow. Thank you so much! It works now. Do you mind me asking another question? How do you refresh data in the datagridview? Neither datagridview1.refresh(); nor datagridview1.update(); works for me – huehuehue Aug 04 '15 at 20:30
  • If you are using exact matching and you mean refreshing your data after emptying the search box: see the edit to my answer. If you have something else in mind, it may require more information and possibly posting a separate question if it's a significant amount of info. – OhBeWise Aug 04 '15 at 20:41
  • I used 3th method but the compiler always show up error `Object reference not set to an instance of an object`. What causes this? – Travis Su Sep 19 '18 at 04:06
  • @TravisSu That is a [`NullReferenceException`](https://stackoverflow.com/a/4660186/3773066). One of the objects you are accessing is likely not initialized. – OhBeWise Sep 21 '18 at 02:52
  • @OhBeWise do I need to initialized `DataTable` and `DefaultView` ? – Travis Su Sep 22 '18 at 01:42
1

Simply create a new query against the database in which you populated the grid?

Use the textbox text with LIKE

Edit:

If you want the grid to update with the search, use AJAX.

Chris
  • 99
  • 3
  • 14
1

OhBeWise answer is the best but until i add something to get points i'm not allowed to like it.

so i'll add this, remember in OhBeWise's answer that your filtering the rows to be listed but using the column name from the query. the query used to set the datasource of the datagridview.

For Instance in my example "LoginID" is in the select statement.

(dataGridViewTheToGrid.DataSource as DataTable).DefaultView.RowFilter = string.Format("LoginID LIKE '{0}%'", textBoxFindUserID.Text);
Renats Stozkovs
  • 2,549
  • 10
  • 22
  • 26
dcarl661
  • 177
  • 3
  • 9
1

In addition if you want a multi-column search use this code

(dataGridView1.DataSource as DataTable).DefaultView.RowFilter = string.Format("Name LIKE '%{0}%' OR ID LIKE '%{0}%'", searchTextBox.Text);
Abdulhakim Zeinu
  • 3,333
  • 1
  • 30
  • 37