3

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?

wallyk
  • 56,922
  • 16
  • 83
  • 148
Nhuren
  • 503
  • 2
  • 10
  • 29

3 Answers3

5

If your DataGridView is bound to a DataTable or a DataView, you can do this:

Create a BindingSource and make BindingSource.DataSource the Datatable or DataView that your DGV is currently using. Then set your DataGridView.DataSource to the BindingSource. Then you can use the BindingSource.Filter property to query your datasource by setting the BindingSource.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.

David Hall
  • 32,624
  • 10
  • 90
  • 127
alexD
  • 2,368
  • 2
  • 32
  • 43
0
        private void txtsearchgroup_KeyUp(object sender, KeyEventArgs e) {
        SqlConnection objconnection = new SqlConnection(servername and ...);
        DataView Dv = new DataView();
        objcommand = new SqlCommand("select name from groupitems", objconnection);
        objdataadapter = new SqlDataAdapter();
        objdataadapter.SelectCommand = new SqlCommand();
        objdataadapter.SelectCommand = objcommand;
        objdataset = new DataSet();
        objconnection.Open();
        objdataadapter.Fill(objdataset);
        Dv.Table = objdataset.Tables[0];
        Dv.RowFilter = " name LIKE '%" + txtsearchgroup.Text + "%'";
        dataGridView1.DataSource = Dv;
        objconnection.Close(); }
  • txtsearchgroup : name of textbox for search word in datagridview1 and
  • txtsearchgroup_KeyUp : event of keyup for search and filter word in datagridview1 and
  • select name from groupitems : name is field for groupitems table and
  • Dv.Table = objdataset.Tables[0] : zero (0) is first table in dataset
kleopatra
  • 51,061
  • 28
  • 99
  • 211
anfd
  • 121
  • 2
  • 11
0

Use the DataView.RowFilter property.

Also take a look at DataTable.DefaultView

Take a look at this article I wrote some time back on filtering data real time.

Ranhiru Jude Cooray
  • 19,542
  • 20
  • 83
  • 128