Sort Data by a Custom Field

This tutorial demonstrates how to implement custom logic for sorting report data if the standard sorting algorithms do not suit your requirements. To accomplish this task, create a calculated field, handle its CalculatedField.GetValue event to evaluate the required value, and then sort the report's data against this field. In this example, report data is sorted by category names based on a custom rule. For more examples, see How to custom sort items in a report.

SortByCalculatedField_Result

Do the following to sort a report's data based on a custom rule:

  1. Start with a report that is bound to the Categories table of the sample Northwind database (the nwind.mdb file included with the XtraReports installation). To learn more about binding a report to a data source, see Provide Data to Reports.
  2. To create a calculated field, switch to the Field List, right-click any item inside the data source node and select Add Calculated Field in the invoked context menu.

    AddCalculatedField_CategoriesTable

  3. Provide a custom logic to evaluate a value for the created calculated field. Declare an array that has category names in a sequence based on the required criterion. In the CalculatedField.GetValue event handler, obtain the current category name using the GetValueEventArgs.GetColumnValue method of the event argument. Then, get the index of this category in the array and assign it to the GetValueEventArgs.Value property.

    ArrayList sortRule = new ArrayList() { "Produce", "Meat/Poultry", "Dairy Products",
        "Grains/Cereals", "Seafood", "Confections", "Condiments", "Beverages" };
    
    private void calculatedField1_GetValue(object sender, GetValueEventArgs e) {
        object category = e.GetColumnValue("CategoryName");
        e.Value = sortRule.IndexOf(category);
    }
    
  4. Next, sort data by the created calculated field using the Group and Sort panel. To do this, click Add a Sort and select the calculated field in the invoked drop-down menu. In the Sort Order drop-down list, define the sort order.

    SortByCalculatedField

  5. Switch to the Field List and drop the required data fields onto the report's Detail band.

    SortByCalculatedField_ReportLayout