How to Search DataGridView by using ComboBox and TextBox in C#

By FoxLearn 11/27/2024 9:08:31 AM   14.72K
To filter a DataGridView in C# using a ComboBox and a TextBox, you can follow these steps.

In this article, we will walk through how to implement filtering functionality for a DataGridView control in a C# Windows Forms application using a ComboBox and a TextBox. The idea is to allow users to filter data in the DataGridView based on a selected column from the ComboBox and a search term entered in the TextBox.

How to Search DataGridView by using ComboBox and TextBox in C#?

Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "SearchDataGridViewUsingComboBoxTextBox" and then click OK

Drag and drop the Lable, Combobox, TextBox and DataGridView controls from the Visual Toolbox onto your form designer, then design your form as shown below.

c# search datagridview

Create a new dataset, then add a Product table from Northwind database to your dataset

c# dataset

A BindingSource is used to manage the connection between the DataGridView and the data source, allowing easy filtering.

In the Form1_Load method, data is loaded into the BindingSource using the productsTableAdapter.Fill() method. This will populate the DataGridView with product data.

// Form load event to populate data
private void Form1_Load(object sender, EventArgs e)
{
    // TODO: This line of code loads data into the 'database.Products' table. You can move, or remove it, as needed.
    this.productsTableAdapter.Fill(this.database.Products);
    cboColumn.SelectedIndex = 1;
}

The ComboBox (cboColumn) is set to a default index (1), which corresponds to the column that we want to use as the default filter column (e.g., ProductName).

The txtSearch_KeyDown event handler is triggered when a key is pressed in the TextBox. It checks whether the user has pressed the Enter key.

// Event handler for KeyDown event in the search TextBox
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
    /// Check if the Enter key is pressed
    if (e.KeyCode == Keys.Enter)
    {
        // Check if the search TextBox is empty
        if (string.IsNullOrEmpty(txtSearch.Text))
            productsBindingSource.Filter = string.Empty; // Clear the filter if the TextBox is empty
        else
            productsBindingSource.Filter = string.Format("{0}='{1}'", cboColumn.Text, txtSearch.Text); // Apply filter based on the selected column and the search term
    }
}

This example demonstrated how to filter data based on the selected column and the search term entered by the user, providing a seamless search experience within a DataGridView.

VIDEO TUTORIAL