I want to put a search option in DataGridView, i.e., User types the string or int in TextBox and similar records the DataGridView should be highlighted. I tried it using KeyPress event but didn’t work.
if (Char.IsLetter(e.KeyChar))
{
for (int i = 0; i < (dgemployee.Rows.Count); i++)
{
if (dgemployee.Rows[i].Cells["Employee"].Value.ToString().
StartsWith(e.KeyChar.ToString(), true,
CultureInfo.InvariantCulture))
{
dgemployee.Rows[i].Cells[0].Selected = true;
return;
}
}
Actually, I need to search the whole DataGridView, not only one column and row. So any best solution?
If your DataGridView is bound to a DataTable or a DataView, you can do this:
Create a BindingSource and make
BindingSource.DataSourcethe Datatable or DataView that your DGV is currently using. Then set yourDataGridView.DataSourceto the BindingSource. Then you can use theBindingSource.Filterproperty to query your datasource by setting theBindingSource.Filterto your query string which will automatically filter the DGV. You can find the syntax here – it is very similar to basic SQL queries, except you can only use wild cards on the beginning and end of the string.