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

时间秒杀一切 提交于 2020-01-02 08:56:09

问题


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();

    _myDbContext.Users.Load();

    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";

or

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.


回答1:


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



来源:https://stackoverflow.com/questions/23309112/ef-in-winforms-how-to-filter-data-in-bindingsource-dgw-local-tobindinglist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!