Daniel

Daniel

  • 1.9k
  • 2
  • 282

How to filter datagridview using multiple combobox c#?

Dec 9 2018 5:32 AM
Hi all!
 
I am very new to coding and am trying to learn C# through little project. I spent a week or more trying to find solution but although there is many threads, none of them made sense for me and couldn't get it to work.

I have a form with datagridview and I want to create 6 comboboxes to filter it. All with same data source. I managed so far to get datagridview working with one combobox but don't know how to add more of them.

I'd much appreciate you help. 

Below is the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
 
namespace TM_Hub
{
   public partial class frmEmpList : Form
   {
      public frmEmpList()
      {
         InitializeComponent();
      }
      private void frmEmpList_Load(object sender, EventArgs e)
      {
         this.PopulateCombobox();
         this.PopulateDataGridView();
      }
      private void PopulateCombobox()
      {
         string qry = "SELECT DISTINCT LastName FROM Employees";
         string constr = @"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial          Catalog=PeopleManager;Integrated Security=True";
         using (SqlConnection con = new SqlConnection(constr))
         {
            using (SqlDataAdapter sda = new SqlDataAdapter(qry, con))
            {
               DataTable dt = new DataTable();
               sda.Fill(dt);
               DataRow row = dt.NewRow();
               row[0] = "";
               dt.Rows.InsertAt(row, 0);
               cbLastName.DataSource = dt;
               cbLastName.DisplayMember = "LastName";
               cbLastName.ValueMember = "LastName";
              }
           }
      }
      private void PopulateDataGridView()
      {
         string query = "SELECT EmpID, FirstName, LastName, Role, Grade, Dept, Shift          FROM Employees";
         query += " WHERE LastName = @LastName";
         query += " OR ISNULL(@LastName, '') = ''";
         string constr = @"Data Source=DESKTOP-Q2B3UUH\SQLEXPRESS;Initial          Catalog=PeopleManager;Integrated Security=True";
         using (SqlConnection con = new SqlConnection(constr))
         {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
               cmd.Parameters.AddWithValue("@LastName", cbLastName.SelectedValue);
               using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
               {
                  DataTable dt = new DataTable();
                  sda.Fill(dt);
                  dgEmpList.DataSource = dt;
               }
            }
         }
      }
      private void cbLastName_SelectionChangeCommitted(object sender, EventArgs e)
      {
         this.PopulateDataGridView();
      }
   }
}
 
 
Many thanks in advance! 

Answers (1)