Hi folks,
I have been working with Entity Framework and binding for quite a while now. When suddenly the following struck me: A
BindingSource
has
Sort
and
Filter Properties
.
These are only supported when the bound
Object Implements IBindingList
or
IBindingListView
. A standard
List<T>
does not
Implement
these. A
BindingList<T>
only
Implements IBindingList
and thus only supports Sorting.
So how can I support Filtering? By binding to a
DataView
.
However, LINQ only supports
ToArray
,
ToDictionary
,
ToList
and
ToLookup
. No
ToBindingList
and certainly no
ToDataView
. I could use
ToList
and pass the
List<T>
to a
BindingList
. To create a
DataView
I'll have to take some more trouble, but I'll manage. So where is the problem?
Let's just say I have the following code:
BindingSourceCustomers.DataSource = context.Customers.ToList();
BindingSourceOrders.DataSource = BindingSourceCustomers;
BindingSourceOrders.DataMember = "Orders";
Let's assume I have a master-detail relation and both are shown in a seperate
DataGridView
. The first grid would now successfully show all customers and the second grid is now displaying all the orders for the customer selected in grid1. Great!
Except now I only want to see customers whose name starts with A.
Remember that I can't use the
Filter Property
of my
BindingSource
. But this is still easy to fix. Just change the first line of code to:
BindingSourceCustomers.DataSource = context.Customers.Where(c => c.Name.StartsWith("A")).ToList();
But now comes the problem. In my second grid I only want to show the orders that are more than $100. My
BindingSource
is getting ALL the orders for each customer automatically. However, I only want to show a selection of the orders.
One way to get around this is by refreshing the bindings for the orders when I click on a row in the customers grid. Seems like a not so elegant solution.
Another solution is to create a
Property
on my
Customer Object
that returns all
Orders
over $100, but that would mean I am very limited in my sorting options and that my sorting options are all known at designtime.
Another possible solution (maybe) is by somehow binding to an
IQueryable
, although I wouldn't know how to do this, or if it is even possible at all in this context.
When using
DataSets
and
DataTables
all this was no problem because they support filtering on the
BindingSource
(it's kind of like getting 'between' binding). Surely I shouldn't be needing
DataSets
to support easy filtering?
I searched on the internet, but did not find a clear solution. Most did not focus on filtering details like this.
I could also not find any filtering options on the
DataGridView
other than using the
Filter Property
of the
BindingSource
.
Any help and tips are welcome.
Thanks :)