Back to Devexpress

How to: Implement Custom Sorting

windowsforms-3071-controls-and-libraries-data-grid-examples-sorting-and-grouping-how-to-implement-custom-sorting.md

latest2.1 KB
Original Source

How to: Implement Custom Sorting

  • Nov 13, 2018

The following example shows how to implement custom sorting with the ColumnView.CustomColumnSort event. In the example, when an ItemFolderDescription column is sorted, the data will be sorted against an IsEmptyRow field instead.

It is assumed that custom sorting is enabled for the ItemFolderDescription column (its GridColumn.SortMode property is set to ColumnSortMode.Custom).

csharp
using DevExpress.XtraGrid.Views.Grid;

void gridView1_CustomColumnSort(object sender, 
DevExpress.XtraGrid.Views.Base.CustomColumnSortEventArgs e) {
    GridView view = sender as GridView;
    if(view == null) return;
    try {
        if (e.Column.FieldName == "ItemFolderDescription") {
            object val1 = view.GetListSourceRowCellValue(e.ListSourceRowIndex1, "IsEmptyRow");
            object val2 = view.GetListSourceRowCellValue(e.ListSourceRowIndex2, "IsEmptyRow");
            e.Handled = true;
            e.Result = System.Collections.Comparer.Default.Compare(val1, val2);
        }
    }
    catch (Exception ee) {
        //...
    }
}
vb
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Grid

Private Sub GridView1_CustomColumnSort(ByVal sender As System.Object, _
ByVal e As CustomColumnSortEventArgs) Handles GridView1.CustomColumnSort
    Dim view As GridView = sender
    If view Is Nothing Then
        Return
    End If
    Try
        If e.Column.FieldName = "ItemFolderDescription" Then
            Dim val1 As Object = view.GetListSourceRowCellValue(e.ListSourceRowIndex1, "IsEmptyRow")
            Dim val2 As Object = view.GetListSourceRowCellValue(e.ListSourceRowIndex2, "IsEmptyRow")
            e.Handled = True
            e.Result = System.Collections.Comparer.Default.Compare(val1, val2)
        End If
    Catch ee As Exception
    '...
    End Try
End Sub