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