C# .NET - Filter Datagridview based on text entered in the textBox using C# winforms

Asked By Austine on 26-Jun-12 07:31 AM
Hi all , Please i will like to know how to filter Datagridview in C# winforms based on text Entered in the textBox using C#.

Please help

Thank you
Lalit M replied to Austine on 26-Jun-12 07:43 AM
show this code sample
----------------------------
namespace DataGrid1
{
    public partial class Form1 : Form
    {
      public Form1()
      {
        InitializeComponent();

        dataGridView1.Rows.Add(3);

        dataGridView1.Rows[0].Cells[0].Value = "find_name";
        dataGridView1.Rows[0].Cells[1].Value = 25;

        dataGridView1.Rows[1].Cells[0].Value = "find_emp_id";
        dataGridView1.Rows[1].Cells[1].Value = 12;

        dataGridView1.Rows[2].Cells[0].Value = "find_job_title";
        dataGridView1.Rows[2].Cells[1].Value = 30;

      }
    }
}
                 
Jitendra Faye replied to Austine on 26-Jun-12 08:18 AM
For this you need to send textBox value as search key.


Use this code-

protected void Button1_Click(object sender, EventArgs e)
    {
     SqlConnection con = new SqlConnection("Your connection string");
      SqlDataAdapter da;

      string query = "SELECT * FROM emptable where UserName='" + TextSearch.Text + "' ";

      da = new SqlDataAdapter(query, con);

      con.Open();
      DataSet ds = new DataSet();
      da.Fill(ds);

     DataGrid1.DataSource = ds.Tables[0];

    }


dipa ahuja replied to Austine on 26-Jun-12 02:19 PM
you can use the dataview to filter rows
DataView dv;
 
void bind()
{
  SqlDataAdapter da = new SqlDataAdapter("select query", "Connectionstring");
  DataTable dt = new DataTable();
 
  da.Fill(dt);
  dv = dt.DefaultView;
  dataGridView1.DataSource = dv;    
}
 
call this bind method in just form load and then implement the textChange Event
 
private void textBox1_TextChanged(object sender, EventArgs e)
{
  if (textBox1.Text == "")
  {
  dv.RowFilter = "";
  }
  else
  {
  dv.RowFilter = "name like '" + textBox1.Text.Trim() + + "%' OR city like '" + .textBox1.Text.Trim() + "%'";
  }
}
 
sathish kumar replied to Jitendra Faye on 09-Dec-13 09:36 AM
Thanks duded....lots of thanks for u....