Thursday, February 19, 2015
Filtering DataGridView by Textbox change in C#
In this article, I will show you how to filter a DataGridView when typing in Textbox. One column value should be used to check the word pattern when filtering. Here, I used first_name column values to apply the filtering process. When you type word pattern in Textbox, it will only show the rows which has same pattern with the entered word.
Open a New Project and create a Windows Form Application and add a Textbox and DataGridView.
Call the following method from the Form_Load method to fill the DataGridView from Database.
Declare a DataSet object called ds as global variable.
private void fillDataGridView() {
// string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string connectionString = "Server=localhost\\sqlexpress;Database=test;User Id=sa;Password=abc123;";
string sql = "SELECT * FROM student";
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "test");
connection.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "test";
}
Double click on the Textbox to create it's TextChange event (In my case txtSearch_TextChanged).
Then add the below code segment to that method.
DataView dataView = new DataView(ds.Tables[0]);
dataGridView1.DataSource = dataView;
dataView.RowFilter = string.Format("first_name LIKE '{0}%'", txtSearch.Text);
dataGridView1.DataSource = dataView;
You can also change {0}% into %{0}% and %{0}
Now you can check the run the project.
Do not forget to leave your comments below.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment