Iason
Iason

Reputation: 249

Add "Contains" filter to existing list of filters in datagridview

I am currently allowing the user to filter through values of a datagridview, by letting them choose the column name, operand, and value.

Column name, operand and value get saved to a ColumnFilter instance. The user is also able to set more than one filters to the grid. My actual filtering works like so:

public void ApplyFilters(List<ColumnFilter> filters)
    {
        BindingSource bs = (BindingSource)dataGridView1.DataSource;
        bs.Filter  = string.Join(" AND ", filters.Select(filter=>string.Format("{0} {1} '{2}'", filter.ColumnName, filter.Operand, filter.Value)).ToArray());
        dataGridView1.DataSource = bs;
    }

This works fine for as many filters as you might want to apply. My current list of available operands is : {=, >, <, >=,<=,<>}. Now however I would like to add one more operand, the Contains. So if someone wants to search through a string column, they can do it through this operand.

One simple way to filter for the Contains is:

var dt = (DataTable)dataGridView1.DataSource;
        dt.DefaultView.RowFilter = string.Format("Column like '%{0}%'", txtBoxSearch.Text.Trim().Replace("'", "''"));
        dataGridView1.DataSource = dt;

This is just an example. How can I make my ApplyFilters function generic enough to cater for the Contains operand?

Upvotes: 0

Views: 1561

Answers (1)

Crowcoder
Crowcoder

Reputation: 11514

Just before setting the binding source filter, set the filter.Value conditionally.

filter.Value = filter.Operand == "like" ? "'%" + filter.Value + "%'" : filter.Value;

However, flexible filtering is still more complicated than this. What if your column is not text data?

Update

Instead of what I said, put that expression inside your Select

bs.Filter  = string.Join(" AND ", 
    filters.Select(filter=>string.Format("{0} {1} '{2}'", 
    filter.ColumnName, filter.Operand, 
    filter.Operand == "like" ? "'%" + filter.Value + "%'" : filter.Value)).ToArray());

Upvotes: 3

Related Questions