This documentation is archived and is not being maintained.

How to: Filter Data in a View

This example shows how to filter data in a view.

To create a filter, define a method that provides the filtering logic. The method is used as a callback and accepts a parameter of type object. The following method returns all the Order objects with the filled property set to "No", filtering out the rest of the objects.


Public Function Contains(ByVal de As Object) As Boolean
    Dim order1 As Order = TryCast(de, Order)
    Return (order1.Filled Is "No")
End Function


You can then apply the filter, as shown in the following example. In this example, myCollectionView is a ListCollectionView object.


Me.myCollectionView.Filter = New Predicate(Of Object)(AddressOf Me.Contains)


To undo filtering, you can set the Filter property to null:


Me.myCollectionView.Filter = Nothing


For information about how to create or obtain a view, see How to: Get the Default View of a Data Collection. For the complete example, see Sorting and Filtering Items in a View Sample.

If your view object comes from a CollectionViewSource object, you apply filtering logic by setting an event handler for the Filter event. In the following example, listingDataView is an instance of CollectionViewSource.


AddHandler listingDataView.Filter, AddressOf ShowOnlyBargainsFilter


The following shows the implementation of the example ShowOnlyBargainsFilter filter event handler. This event handler uses the Accepted property to filter out AuctionItem objects that have a CurrentPrice of $25 or greater.


Private Sub ShowOnlyBargainsFilter(ByVal sender As Object, ByVal e As FilterEventArgs)
    Dim product As AuctionItem = CType(e.Item, AuctionItem)
    If Not (product Is Nothing) Then
        'Filter out products with price 25 or above
        If product.CurrentPrice < 25 Then
            e.Accepted = True
        Else
            e.Accepted = False
        End If
    End If
End Sub


Show: