Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter DataGridView in C# Win Forms?

I have created a simple DataGridView through the toolbox and have selected data through the wizard (no code in .cs file) from a database. It is working flawlessly as you can see in the picture below: DataGridView1

Now I want to filter the entries in it by contact person name. I have a textbox and search button so when the user enters a "contact person name" such as "Altaf" and then clicks on search, the GridView should refresh and only entries with ticketid=4 should appear.

The only code in the .cs file (which is auto-generated) is:

private void Form2_Load(object sender, EventArgs e)
{ 
    this.tblTicketDetailTableAdapter.Fill(this.sTDataSet1.tblTicketDetail); //auto-generated
}

I tried this in a ButtonClick event as suggested by someone but it generates the error: "Cannot interpret token '{' at position 27"

BindingSource bs = new BindingSource();
bs.DataSource = dataGridView1.DataSource;
bs.Filter = issuerNameDataGridViewTextBoxColumn + "like '%" + txtbxSearch.Text.Trim().Replace("'", "''") + "%'";
dataGridView1.DataSource = bs.DataSource;

I have no experience in DataGridViews or WinForms coding, so please explain in detail.

like image 517
Shajee Afzal Avatar asked Dec 01 '22 19:12

Shajee Afzal


2 Answers

Thank you everyone that has answered to my query, I really appreciate your help guys. You guys are the most helpful bunch.

I have solved my problem by doing following modifications to my code :

    public void btnSearch_Click(object sender, EventArgs e)
    {
        BindingSource bs = new BindingSource();
        bs.DataSource = dataGridView1.DataSource;
        bs.Filter = dataGridView1.Columns[5].HeaderText.ToString() + " LIKE '%" + txtbxSearch.Text + "%'";
        dataGridView1.DataSource = bs;
    }

Thank you again.

like image 154
Shajee Afzal Avatar answered Dec 03 '22 08:12

Shajee Afzal


Try this:

foreach (System.Windows.Forms.DataGridViewRow r in MyGridView.Rows)
{
      if ((r.Cells[5].Value).ToString().ToUpper().Contains(searchText.ToUpper()))
      {
            MyGridView.Rows[r.Index].Visible = true;
            MyGridView.Rows[r.Index].Selected = true;
      }
      else
      {
            MyGridView.CurrentCell = null;
            MyGridView.Rows[r.Index].Visible = false;
      }
 }
like image 21
Raging Bull Avatar answered Dec 03 '22 08:12

Raging Bull