ripper234
ripper234

Reputation: 230008

Filtering DataGridView rows in .Net

I have a DataGridView that is displaying a List of objects (not DataSet). Is there an easy way to set a filter, so the DGV will only display rows that match the filter?

IList<T> log = ...;
dgv.DataSource = log;

Upvotes: 1

Views: 2569

Answers (2)

Marc Gravell
Marc Gravell

Reputation: 1062550

Do you have LINQ available? If so, one option is:

dgv.DataSource = log.Where(x=>x.IsActive && x.Type == 3).ToList();

However, new/removed rows won't update the original list (edits to existing rows are fine).

If not LINQ, you can do the same with List<T>.FindAll:

dgv.DataSource = log.FindAll(delegate (SomeType x) {
    return x.IsActive && x.Type == 3;});

There is the IBindingListView.SupportsFiltering / IBindingListView.Filter pair, but none of the standard lists (including BindingList<T>) implement this feature.

Upvotes: 3

Quintin Robinson
Quintin Robinson

Reputation: 82325

You could do Log.Where(filter) That's generally how I filter items in a list bound to a DGV if I don't have control over the generation.

Upvotes: 1

Related Questions