Skip to main content

DevExpress v24.2 Update — Your Feedback Matters

Our What's New in v24.2 webpage includes product-specific surveys. Your response to our survey questions will help us measure product satisfaction for features released in this major update and help us refine our plans for our next major release.

Take the survey Not interested

Step 3: Enable Filter Operations

  • 5 minutes to read

You can allow users to filter rows in the GridControl. Complete the following steps:

  1. Implement filter operations in the virtual source.
  2. Enable filter operations in the GridControl.

Virtual Source Tutorial - Filtering

Explore the full source code in the following examples and demos:

Infinite Scrolling Source
View Example Run Demo
Paged Source
View Example Run Demo

#Filter Types

The Issues Service can fetch rows:

  • With a specified Priority.
  • Over a period of time (between CreatedFrom and CreatedTo).
  • With the maximum number of Votes.
C#
public class IssueFilter {  
    public Priority? Priority { get; private set; }
    public DateTime? CreatedFrom { get; private set; }
    public DateTime? CreatedTo { get; private set; }
    public int? MinVotes { get; private set; }
}

The code snippet below fetches rows without filter conditions:

C#
[Command]
public void FetchIssues(FetchRowsAsyncArgs args) {
    args.Result = GetIssuesAsync(args);
}
async Task<FetchRowsResult> GetIssuesAsync(FetchRowsAsyncArgs args) {
    var take = args.Take ?? 30;
    var issues = await IssuesService.GetIssuesAsync(
        skip: args.Skip,
        take: take,
        sortOrder: GetIssueSortOrder(args.SortOrder),
        filter: null
    );

    return new FetchRowsResult(issues, hasMoreRows: issues.Length == take);
}

#Implementation Details

#Create Filter Converter

  1. Create a filter converter.
  2. Obtain the GridControl filter.
  3. Parse the filter and return an IssueFilter (a type used in the Model). A command bound to the InfiniteAsyncSource.FetchRowsCommand uses the filter when the GridControl fetches rows.

    C#
    public class IssueFilterConverter : MarkupExtension, IValueConverter {
        object IValueConverter.Convert(object filter, Type targetType, object parameter, CultureInfo culture) {
            return ((CriteriaOperator)filter).Match(
                binary: (propertyName, value, type) => {
                    if (propertyName == "Votes" && type == BinaryOperatorType.GreaterOrEqual)
                        return new IssueFilter(minVotes: (int)value);
                    if (propertyName == "Priority" && type == BinaryOperatorType.Equal)
                        return new IssueFilter(priority: (Priority)value);
                    if (propertyName == "Created") {
                        if (type == BinaryOperatorType.GreaterOrEqual)
                            return new IssueFilter(createdFrom: (DateTime)value);
                        if (type == BinaryOperatorType.Less)
                            return new IssueFilter(createdTo: (DateTime)value);
                    }
                    throw new InvalidOperationException();
                },
                and: filters => {
                    return new IssueFilter(
                        createdFrom: filters.Select(x => x.CreatedFrom).SingleOrDefault(x => x != null),
                        createdTo: filters.Select(x => x.CreatedTo).SingleOrDefault(x => x != null),
                        minVotes: filters.Select(x => x.MinVotes).SingleOrDefault(x => x != null),
                        priority: filters.Select(x => x.Priority).SingleOrDefault(x => x != null)
                    );
                },
                @null: default(IssueFilter)
            );
        }
        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
            throw new NotImplementedException();
        }
        public override object ProvideValue(IServiceProvider serviceProvider) => this;
    }
    

    Tip

    The code sample above uses the FilterCriteriaMatchHelper.Match method, which allows you to parse filter criteria created by the GridControl.

    The FilterCriteriaMatchHelper is an extension from the DevExpress.Xpf.Grid.v24.2.Extensions.dll library. Refer to the following path for additional information on how extension methods work: c:\Program Files\DevExpress 24.2\XPF\DevExpress.Xpf.Grid\DevExpress.Xpf.Grid.Extensions\.

  4. Assign the filter converter to the DataControlBase.CriteriaConverter property. The filter converter specified in the View allows you to avoid a reference to the DevExpress.Data namespace in your ViewModel.

    xml
    <dxg:GridControl CriteriaConverter="{local:IssueFilterConverter}"/>
    

    If you can reference the DevExpress.Data namespace in your ViewModel, create a method that parses the GridControl filter in the ViewModel.

  5. When you specify the DataControlBase.CriteriaConverter property, the FetchAsyncArgsBase.Filter property returns the filter of the Object type. You can cast this filter to the type returned by the filter converter (IssueFilter in this tutorial).

    C#
    [Command]
    public void FetchIssues(FetchRowsAsyncArgs args) {
        args.Result = GetIssuesAsync(args);
    }
    async Task<FetchRowsResult> GetIssuesAsync(FetchRowsAsyncArgs args) {
        var take = Math.Min(args.Take ?? 30, 100);
        var issues = await IssuesService.GetIssuesAsync(
            skip: args.Skip,
            take: take,
            sortOrder: GetIssueSortOrder(args.SortOrder),
            filter: (IssueFilter)args.Filter
        );
    
        return new FetchRowsResult(issues, hasMoreRows: issues.Length == take);
    }
    

#Obtain Priorities

Get the list of priorities to display them in the Priority column drop-down filter:

Virtual Source Tutorial - Priorities

  1. Create a GetUniqueValues command.
  2. Use the PropertyName property to get the field name for which the GridControl collects unique values.
  3. Get the list of unique values and assign it to the Result property.
  4. Bind the command to the InfiniteAsyncSource.GetUniqueValuesCommand.
C#
[Command]
public void GetUniqueValues(GetUniqueValuesAsyncArgs args) {
    if(args.PropertyName == "Priority") {
        var values = Enum.GetValues(typeof(Priority)).Cast<object>().ToArray();
        args.Result = Task.FromResult(values);
    } else {
        throw new InvalidOperationException();
    }
}
xml
<dxg:GridControl CriteriaConverter="{local:IssueFilterConverter}">
    <dxg:GridControl.ItemsSource>
        <dx:InfiniteAsyncSource ElementType="{x:Type local:IssueData}"
                                FetchRowsCommand="{Binding FetchIssuesCommand}"
                                GetUniqueValuesCommand="{Binding GetUniqueValuesCommand}"/>
    </dxg:GridControl.ItemsSource>
    <!-- ... -->
</dxg:GridControl>

If a service or database includes a method that obtains unique values, use this method in the GetUniqueValues command.

#Enable Priority Column Filtering

Allow users to filter GridControl rows by the Priority column as follows:

  1. Set the ColumnBase.AllowedBinaryFilters property to Equals to allow users to display rows with the specified priority.

  2. Set the ColumnBase.FilterPopupMode property to List to enable a drop-down filter that allows users to select one item at a time.

xml
<dxg:GridColumn FieldName="Priority" 
                AllowedBinaryFilters="Equals" 
                FilterPopupMode="List"/>

Virtual Source Tutorial - Filtering "Votes" Column

#Enable Votes Column Filtering

Allow users to filter GridControl rows by the Votes column as follows:

  1. Set the ColumnBase.AllowedBinaryFilters property to GreaterOrEqual to allow users to display rows with votes that are greater than or equal to an input value.

  2. Set the ColumnBase.FilterPopupMode property to Excel to enable a drop-down filter that allows users to create the GreaterOrEqual criteria.

xml
<dxg:GridColumn FieldName="Votes" 
                AllowedBinaryFilters="GreaterOrEqual" 
                FilterPopupMode="Excel"/>

Virtual Source Tutorial - Filtering "Votes" Column

#Enable Created Date Column Filtering

Allow users to filter GridControl rows by the Created Date column as follows:

  1. Set the ColumnBase.AllowedDateTimeFilters property to SingleDateRange to allow users to filter rows by a single date or a date range.

  2. Set the ColumnBase.FilterPopupMode property to DateSmart to enable a calendar that allows users to specify dates.

xml
<dxg:GridColumn FieldName="Created" 
                AllowedDateTimeFilters="SingleDateRange" 
                FilterPopupMode="DateSmart"/>

Virtual Source Tutorial - Filtering "Created Date" Column

#Continue

Tutorial 4: Display Summaries