Search code examples
c#winformsoledbdataadapter

How to search in DataGridView using access database?


I am working on a winform database application that update data using access database. In which I am trying to add textbox to search and filter data in datagridview (I connect my datagridview to Access Database using OleDb dataadapter. My code for search text box is as follows:

private void txtSearchAdmin_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
        {
            if (string.IsNullOrEmpty(txtSearchAdmin.Text))
                dataGridView.DataSource = employeesBindingSource;
            else
            {
                var query = from o in this.adminData.Employees
                            where o.Customer_Name.Contains(txtSearchAdmin.Text) || o.Phone == txtSearchAdmin.Text || o.Address.Contains(txtSearchAdmin.Text)
                            select o;
                dataGridView.DataSource = query.ToList();
          }
        }

Solution

  • @Abhi you currently using KeyPress event and this event fires before enter the text in the textbox, so you should use textbox TextChanged event.

    private void txtSearchAdmin_TextChanged(object sender, EventArgs e)
        {
    
                if (string.IsNullOrEmpty(txtSearchAdmin.Text))
                    dataGridView.DataSource = employeesBindingSource;
                else
                {
                    var query = from o in this.adminData.Employees
                                where o.Customer_Name.Contains(txtSearchAdmin.Text) || o.Phone == txtSearchAdmin.Text || o.Address.Contains(txtSearchAdmin.Text)
                                select o;
                    dataGridView.DataSource = query.ToList();
              }
    
    }