Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search in Data gridview in C# Windows Form application?

I have a form in which a simple gridview is populated by a table in database having columns like TicketID, Name, Company, Product etc. Now I want to add a search feature so that user could search by customer name or company or TicketID.

How can I do that ? I want to place a combox box, textbox and a simple "search" button above datagrid. When the user selects TicketID for example, enters "1" in textbox and presses "Search", it should refresh datagrid with entry where TicketID = 1.

Now I don't have any idea on how to implement it. Googled for it but found nothing useful. So any help in this regard will be appreciated.

Regards.

like image 986
Shajee Afzal Avatar asked Dec 02 '22 17:12

Shajee Afzal


2 Answers

You may look into:

BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = columnNameToSearch + " like '%" + textBox1.Text + "%'";
dataGridView1.DataSource = bs;

This will show you records containing text from textbox1 in column of your choice. I did exactly what you are asking for:)

like image 188
Łukasz Motyczka Avatar answered Dec 04 '22 06:12

Łukasz Motyczka


Create a Textbox for search input and use the following code on its TextChanged event

private void txtSearch_TextChanged(object sender, EventArgs e)
{
    (dataGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("TicketID like '{0}%' OR Product like '{0}%' OR Name like '{0}%' OR Product like '{0}%'", txtSearch.Text);
}
like image 25
Sabri Avatar answered Dec 04 '22 07:12

Sabri