EF in WinForms: how to filter data in BindingSource/DGW (.Local.ToBindingList())

ado.net c# entity-framework entity-framework-6 winforms


I generated an EF model (Database first) and DataSource following this tutorial http://msdn.microsoft.com/en-us/data/jj682076.aspx

On my form I created BindingSource (bsUsers) and bound DataGridView to it.

Here is how I load data on form startup:

    _myDbContext = new MyDbContext();


    bsUsers.DataSource = _myDbContext.Users.Local.ToBindingList();

It works, I can add and modify records using DataGridView and other bound controls.

But the thing I didn't figure out is how to filter data. For example I want to have textbox where I can type user name (or part of it) and it will hide all other records.

Looks like BindingList that is returned by ToBidingList() method doesn't support filtering?

I tried this

bsUsers.Filter = "Id = 1";


bsUsers.Filter = "Username like 'admin'";

But no effect. UPD: and bsUsers.SupportsFiltering is false.

I have googled but found only this topic MSDN topic where they suggest to filter data before loading (Users.Where(...).Load()), and that's not what I need. I want to load all records and then allow to filter it.

4/26/2014 10:35:54 AM

Accepted Answer

The Filter property of the BindingSource only works with lists that implement the IBindingListView interface. Since BindingList only implements IBindingList (which has no filtering capabilities) the Filter property does nothing.

Either load your data into something like a List<User> and provide the bsUsers.DataSource with filtered elements of the list, e.g. users.Where( u=> u.Id == 1 ).ToList() or replace your BindingList by a list that implements IBindingListView. Possible pointers from here: Generic IBindingListView Implementations

5/23/2017 11:46:04 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow