In this example, I’ll show you How to Filter DataGridView With the Text Entered in TextBox.
Step 1: Create a new Windows application. Add a DataGridView and textbox control.
Step 2: Load data from DataTable. (Form_Load)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
DataTable table; private void Form1_Load(object sender, EventArgs e) { table = new DataTable(); table.Columns.Add("Id", typeof(int)); table.Columns.Add("FirstName", typeof(string)); table.Columns.Add("LastName", typeof(string)); table.Columns.Add("City", typeof(string)); table.Rows.Add(1, "Leon", "Ardon", "Paris"); table.Rows.Add(2, "Ben", "Jamir", "London"); table.Rows.Add(3, "Samuel", "Toe", "Berlin"); table.Rows.Add(4, "Lila", "Foe", "Madrid"); dataGridView1.DataSource = table; } |
Step 3: Now in the text_changed property of the textbox, add the following code. Here I am filtering it by the column “FirstName”
1 2 3 4 5 6 7 8 |
private void txtSearch_TextChanged(object sender, EventArgs e) { DataView dv = table.DefaultView; dv.RowFilter = "FirstName LIKE '" + txtSearch.Text + "%'"; dataGridView1.DataSource = dv; } |
Output: