简体   繁体   中英

C# apply more than one filter to datagridview

I have a list of filters that the user has input and I want to apply them to my DataGridView . What is the best way to apply all the filters to a DataGridView ? My list of ColumnFilters is basically a list of strings which are broken into : Column name, operand (=, >, < etc.) and the value of the user input.

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

The bindingsource Filter supports AND , so the filters could be combined with something like:

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

(Note: the foreach is not needed when using the above)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM