Skip to main content

Sorting in Code

  • 2 minutes to read

Sort and Unsort Data

GridColumn.SortOrder

Sorts Grid data by this column. Setting this property to None removes sorting by this column.

gridView1.ClearSorting();  
gridView1.Columns["SomeFieldName"].SortOrder = DevExpress.Data.ColumnSortOrder.Ascending; 

ColumnView.SortInfo

A collection that stores specific ColumnSortInfo objects for every grid column involved in sorting and grouping. To sort data by specific columns, modify this collection manually by calling the GridColumnSortInfoCollection.ClearAndAddRange method. The code below illustrates two different approaches to sort Grid data ascending by order dates, and then descending by customer IDs.

gridView1.SortInfo.ClearAndAddRange(new[] {
    new GridColumnSortInfo(colOrderDate, DevExpress.Data.ColumnSortOrder.Ascending),
    new GridColumnSortInfo(colCustomerID, DevExpress.Data.ColumnSortOrder.Descending)
});

//or

colOrderDate.SortOrder = DevExpress.Data.ColumnSortOrder.Ascending;
colCustomerID.SortOrder = DevExpress.Data.ColumnSortOrder.Descending;

ColumnView.BeginSort, ColumnView.EndSort

If you perform multiple sorting operations in code, wrap these code blocks between the BeginSort/EndSort method calls to prevent excessive redraw.

ColumnView.StartSorting, ColumnView.EndSorting

Non-cancelable events that fire when a sorting operation starts and after it is complete.

ColumnView.ClearSorting

Removes all currently applied data sorting.

Custom Sorting

The ColumnView.CustomColumnSort event fires when the Data Grid needs to sort data by a column, whose GridColumn.SortMode property equals Custom. The event allows you to compare rows one-by-one and decide what row should go first. In the example below, the default DateTime column sorting (comparing years, then months and dates) is changed to custom sorting where dates are compared by months and then days, while years are ignored.

Grid - Custom Birth Date Sorting

private void gridView_CustomColumnSort(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnSortEventArgs e) {
    if (e.Column.FieldName == "BirthDate") {
        e.Handled = true;
        int month1 = Convert.ToDateTime(e.Value1).Month;
        int month2 = Convert.ToDateTime(e.Value2).Month;
        if (month1 > month2)
            e.Result = 1;
        else 
            if (month1 < month2)
                e.Result = -1;
            else e.Result = System.Collections.Comparer.Default.Compare(Convert.ToDateTime(e.Value1).Day, Convert.ToDateTime(e.Value2).Day);
    }
}
See Also