Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I filter a BindingSource with a LINQ query as the DataSource

I'm having trouble getting a filter to work on a BindingSource that is the DataSource for a DataGridView control. Basically, I have LINQ query that is the DataSource for the BindingSource and I would like to filter down the results. Below is an example of what I'm trying to accomplish.

Dim query = From row In dataTable _
            Select New MyRow(row)

Dim bs As New BindingSource()
bs.DataSource = query.ToList()

grid.DataSource = bs

bs.Filter = "Col1 = 'value'"

...

Public Class MyRow
    Private _key As String
    Private _col1 As String

    Public Sub New(ByVal row As DataTableRow)
        _key = GetNewKeyValue()
        _col1 = row.Col1
    End Sub

    Public ReadOnly Property Key() As String
        Get
            Return _key
        End Get
    End Property

    Public ReadOnly Property Col1() As String
        Get
            Return _col1
        End Get
    End Property
End Class

So, I can see all the rows in the DataGridView control but the filter doesn't have any effect. If I switch the BindingSource's DataSource to use a DataTable, then the filtering works as expected. What am I missing?

like image 272
Utensil Avatar asked Apr 23 '09 18:04

Utensil


People also ask

What is the LINQ query operator used to filter data?

Filtering operators are those operators which are used to filter the data according to the user requirement from the given data source or from the given sequence. For example, in an employee record, we want to get the data of the employees whose age in 21.

Can you use a DataView to filter rows in a DataTable?

Using a DataView, you can expose the data in a table with different sort orders, and you can filter the data by row state or based on a filter expression. A DataView provides a dynamic view of data in the underlying DataTable: the content, ordering, and membership reflect changes as they occur.

Where clause in DataView?

The expression in the Where clause is used to determine which data rows will be included in the DataView, and is the basis for the filter. Expression-based filters offer more powerful and complex filtering than the simpler string-based filters. The string-based and expression-based filters are mutually exclusive.


1 Answers

From the BindingSource documentation:

Typically used in complex data-binding scenarios, the Filter property allows you to view a subset of the DataSource. Only underlying lists that implement the IBindingListView interface support filtering

like image 81
Sven Künzler Avatar answered Oct 12 '22 15:10

Sven Künzler