How to Add a Search Box to Filter Your WinForms Datagrid
Tags: webdev, devops, dotnet, tutorial
Published: 2023-07-27 14:11:28

---
canonical_url: https://developer.mescius.com/blogs/how-to-add-search-box-to-filter-your-winforms-datagrid
description: Learn how to add a search box to filter your WinForms datagrid application. See more from ComponentOne today.
---
In today’s data-driven world, we commonly use datagrids to manage massive datasets. We can incorporate searching and filtering capabilities within these grids to better explore and analyze data in these grids.

To showcase the implementation, we will consider a scenario where we will be using a [FlexGrid](/componentone/docs/win/online-flexgrid/overview.html) control in a WinForms application. The grid is bound to the NWind database's Products table, shipped with the ComponentOne Samples.

This blog will show you how to incorporate the searching feature in FlexGrid by using the [C1FlexGridSearchPanel](/componentone/docs/win/online-flexgrid/C1.Win.C1FlexGrid.SearchPanel.4.5.2~C1.Win.C1FlexGrid.C1FlexGridSearchPanel.html) control as a search box. Additionally, we will utilize the [C1DataFilter](/componentone/docs/wpf/online-datafilter/overview.html) control to add an enhanced filtering feature to the grid, enabling users to refine the displayed data based on their preferences.

## Filtering the Datagrid Using a Search Panel

We have a special control in our ComponentOne WinForms suite, C1FlexGridSearchPanel, which adds filtering (or searching) capabilities to the FlexGrid control. This control highlights search text and filters the records that contain those texts. The search panel provides various settings that can be set according to the requirement. For example, the [SearchMode](/componentone/docs/win/online-flexgrid/C1.Win.C1FlexGrid.SearchPanel.4.5.2~C1.Win.C1FlexGrid.C1FlexGridSearchPanel~SearchMode.html) property determines how the search is triggered (automatically or upon hitting the Search button). We can also set the [SearchDelay](/componentone/docs/win/online-flexgrid/C1.Win.C1FlexGrid.SearchPanel.4.5.2~C1.Win.C1FlexGrid.C1FlexGridSearchPanel~SearchDelay.html) property to specify the time interval after which the search will be performed automatically.

In the 2023 v1 release, we introduced a new feature in the C1FlexGridSearchPanel control called "highlight all occurrences", which makes it simple for users to discover and visualize all instances of the search word within the grid. This feature provides a convenient overview of data distribution and greatly enhances the user experience.

Here are the steps to add a search panel to FlexGrid for WinForms:

1\. Create a WinForms application and install the "[C1.Win.C1FlexGrid](https://www.nuget.org/packages/C1.Win.C1FlexGrid)" and "[C1.Win.C1FlexGrid.SearchPanel](https://www.nuget.org/packages/C1.Win.C1FlexGrid.SearchPanel)" packages from NuGet.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/kqhjnwmy/01-search.png?width=500&height=233.49244232299125)

2\. Add a FlexGrid control and a FlexGridSearchPanel to the form designer window from the toolbox.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/1tjl0ucl/02-search.png?width=500&height=428.33333333333337)

3\. Bind the FlexGrid control to the desired data source, such as the Products table of the NWind database. We have bound FlexGrid to the data source in the form’s load event handler, as shown in the following code:

```
    private void Form1_Load(object sender, EventArgs e)
    {
        var path = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\ComponentOne Samples\Common";
        var dataAdapter = new OleDbDataAdapter("select ProductID, ProductName, SupplierID, QuantityPerUnit, " +
            "CategoryID, UnitPrice from Products", string.Format(@"provider=Microsoft.ACE.OLEDB.12.0;data source={0}\c1nwind.mdb;", path));
        _dataTable = new DataTable();
        dataAdapter.Fill(_dataTable);
        c1FlexGrid1.DataSource = _dataTable;
    }
```

4\. Set the [C1FlexGridSearchPanel](/componentone/docs/win/online-flexgrid/C1.Win.C1FlexGrid.SearchPanel.4.5.2~C1.Win.C1FlexGrid.C1FlexGridSearchPanel~SetC1FlexGridSearchPanel.html) property of the FlexGrid to the instance of the added C1FlexGridSearchPanel in the FlexGrid’s Properties window.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/u40avmvr/03-search.png?width=448&height=317)

5\. FlexGrid search panel to 'All'. This setting ensures that all instances of the searched string in a cell will be highlighted. We also have the choice to highlight only the first occurrence in the cell or opt for no highlighting by selecting the appropriate "OnlyFirst" or "None" enum options.

```
    c1FlexGridSearchPanel1.HighlightSearchResultsMode = C1.Win.C1FlexGrid.SearchHighlightMode.All;
```

Run the application and test the search panel functionality. Enter search terms in the search box, and the FlexGrid will automatically filter and display the matching data.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/d5pj2u0l/04-search.gif?width=497.47474747474746&height=500)

## Filtering the Datagrid Using a Data Filter

Data filtering in the grid enables users to efficiently explore and analyze enormous datasets by narrowing down specific information of interest, enhancing productivity and data exploration capabilities. This requirement can be achieved using the **C1DataFilter** control, which provides extensive filtering capabilities. It automatically generates different types of filters based on the properties of the data source.

Additionally, it allows us to create custom filters and dynamically replace the default filter editors at runtime, which empowers users to perform precise searches and retrieve the exact data they need.

To implement the data filtering feature to the FlexGrid in the above application, you can follow these steps:

1\. Install the '[C1.Win.DataFilter](https://www.nuget.org/packages/C1.Win.DataFilter/4.8.20231.603#readme-body-tab)' package from NuGet.

2\. Add C1DataFilter control to the designer window from the toolbox.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/dimf4cj5/05-search.png?width=500&height=196.9548133595285)

3\. In the Form’s Load event handler, set the data source of the C1DataFilter control to the same as the data source of the FlexGrid control.

```
    c1DataFilter1.DataSource = _dataTable;
```

4\. Set the [AutoGenerateFilters](/componentone/docs/win/online-datafilter/C1.Win.DataFilter.4.5.2~C1.Win.DataFilter.C1DataFilter~AutoGenerateFilters.html) property of the C1DataFilter to true to create the default filters depending on the type of fields present in the data source.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/5ehpbu24/06-search.png?width=392&height=260)

5\. We have modified the automatically generated filters by subscribing to the DataFilter's [FilterAutoGenerating](/componentone/docs/win/online-datafilter/C1.Win.DataFilter.4.5.2~C1.Win.DataFilter.C1DataFilter~FilterAutoGenerating_EV.html) event and specified the filtering parameters, such as minimum/maximum values for the [RangeFilter](/componentone/docs/win/online-datafilter/C1.Win.DataFilter.4.5.2~C1.Win.DataFilter.RangeFilter.html) and checklist items for the [CheckListFilter](/componentone/docs/win/online-datafilter/C1.Win.DataFilter.4.5.2~C1.Win.DataFilter.ChecklistFilter.html).

```
    private void c1DataFilter1_FilterAutoGenerating(object sender, C1.DataFilter.FilterAutoGeneratingEventArgs e)
            {
                switch (e.Property.Name)
                {
                    case "ProductID":
                        var prodIdFilter = (C1.Win.DataFilter.RangeFilter)e.Filter;
                        prodIdFilter.Maximum = _dataTable.AsEnumerable().Max(x => x.Field<int>("ProductID"));
                        prodIdFilter.Minimum = _dataTable.AsEnumerable().Min(x => x.Field<int>("ProductID"));
                        prodIdFilter.Increment = 1;
                        break;
                    case "ProductName":
                        var productNameFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter;
                        productNameFilter.ShowSearchBox = true;
                        productNameFilter.SelectAll();
                        break;
                    case "SupplierID":
                        var suppIdFilter = (C1.Win.DataFilter.RangeFilter)e.Filter;
                        suppIdFilter.Maximum = _dataTable.AsEnumerable().Max(x => x.Field<int>("SupplierID"));
                        suppIdFilter.Minimum = _dataTable.AsEnumerable().Min(x => x.Field<int>("SupplierID"));
                        suppIdFilter.Increment = 1;
                        break;
                    case "QuantityPerUnit":
                        var qpuFilter = (C1.Win.DataFilter.ChecklistFilter)e.Filter;
                        qpuFilter.ShowSearchBox = true;
                        qpuFilter.SelectAll();
                        break;
                    case "CategoryID":
                        var categoryIdFilter = (C1.Win.DataFilter.RangeFilter)e.Filter;
                        categoryIdFilter.Maximum = _dataTable.AsEnumerable().Max(x => x.Field<int>("CategoryID"));
                        categoryIdFilter.Minimum = _dataTable.AsEnumerable().Min(x => x.Field<int>("CategoryID"));
                        categoryIdFilter.Increment = 1;
                        break;
                    case "UnitPrice":
                        var unitPriceFilter = (C1.Win.DataFilter.RangeFilter)e.Filter;
                        unitPriceFilter.Maximum = Decimal.ToDouble(_dataTable.AsEnumerable().Max(x => x.Field<decimal>("UnitPrice")));
                        unitPriceFilter.Minimum = Decimal.ToDouble(_dataTable.AsEnumerable().Min(x => x.Field<decimal>("UnitPrice")));
                        unitPriceFilter.Increment = 0.01;
                        break;
                    default: break;
                }
            }
```

We have added some additional functionalities to our blog sample application. These include saving the filters applied to the FlexGrid and loading the saved filters as required. Check out this [link](/componentone/docs/win/online-datafilter/xmlserializationdeserialization.html) for more information regarding the same.

Furthermore, we have added an option to enable or disable the automatic filtering of FlexGrid data based on the C1DataFilter and a dedicated button that users can click to apply the filtering to the grid explicitly.

Run the application and test the data filtering functionality.

![WinForms Datagrid Filter](https://files.grapecity.com/gc-website-media/prxnpblk/07-search.gif?width=500&height=322.9859571322986)

Integrate powerful searching and filtering capabilities into FlexGrid to maximize the potential of your WinForms applications, where users can easily navigate through enormous datasets, derive useful insights, and make well-informed decisions with the ability to search, highlight, and filter data. Use these powerful capabilities to transform the way consumers engage with their data.

Download the sample from here: [DataGridSearchFilter.zip](/{localLink:umb://media/2a3104b8582b4868ac1afa11a3f66823} "Search_C1_07/25/23")

If you have any inquiries, please leave them in the comments section below. Happy Coding!