Sorting

23 Sep 2020 / 9 minutes to read

The dataGrid allows sorting on its data by setting the SfDataGrid.AllowSorting property to true. It allows sorting the data against one or more columns. When sorting is applied, the data grid automatically rearranges the data to match with the current sort criteria. When the SfDataGrid.AllowSorting is true, you can sort the data simply by tapping the column header. Once sorting is applied, the data grid shows a sort icon in the respective column header indicating the direction of sorting.

NOTE

To update sorting for newly added row or column, set the SfDataGrid.View.LiveDataUpdateMode to LiveDataUpdateMode.AllowDataShaping.

Programmatic sorting

The data grid also allows sorting from the code. This requires to manually define the SortColumnDescription objects and add it in the SfDataGrid.SortColumnDescriptions collection. The data grid sorts the data based on the SortColumnDescription objects added to this collection.

SortColumnDescription object holds following two properties:

  • ColumnName: Defines the name of the sorted column.
  • SortDirection: Defines an object of type ListSortDirection that defines the sorting direction.

The following code example illustrates this:

  • c#
  • dataGrid.AllowSorting = true;
    
    dataGrid.SortColumnDescriptions.Add (new SortColumnDescription () {
        ColumnName = "OrderID",
        SortDirection = ListSortDirection.Descending
    });

    Tri-state sorting

    In addition to sort the data in ascending/descending orders, the data grid also allows you to unsort the data in the original order by clicking the header again after sorting to descending order by setting the SfDataGrid.AllowTriStateSorting property to true. When this property is set, sorting in each column iterates through three sorting states; ascending, descending, and unsorted.

    The following code example shows how to enable tri-state sorting in the data grid:

  • c#
  • dataGrid.AllowTriStateSorting = true;

    Multi-column sorting

    The data grid allows sorting the data against more than one columns by setting the SfDataGrid.AllowMultiSorting property to true. The number of columns by which the data can be sorted is unlimited. To apply sorting for multiple columns, tap the desired column headers after setting the AllowMultiSorting property.

    The following code example shows how to enable multi-sorting in the data grid:

  • c#
  • dataGrid.AllowMultiSorting = true;

    Sort column by double click

    By default, columns are sorted when the column header clicked. You can change this behavior to sort the column in double click action by setting the SfDataGrid.SortTapAction property as DoubleTap.

    The following code example shows how to set SortTapAction is DoubleTap in the data grid:

  • c#
  • dataGrid.SortTapAction=SortTapAction.DoubleTap;

    The following screenshot shows the sorting functionality in the data grid:

    Sorting events

    The data grid provides the following events for the sorting functionality:

    These two events are triggered with DataGridSortColumnsChangingEventArgs and DataGridSortColumnsChangedEventArgs that contain the following properties:

    • AddedItems: Gets the collection of SortColumnDescription objects added to SortColumnDescriptions collection for Sorting.
    • RemovedItems: Gets the collection of SortColumnDescription objects removed from SortColumnDescriptions collection.

    The following code example illustrates how to hook the SortColumnsChanging event and cancel the sorting of a column:

  • c#
  • dataGrid.SortColumnsChanging += DataGrid_SortColumnsChanging;
  • c#
  • void DataGrid_SortColumnsChanging (object sender, DataGridSortColumnsChangingEventArgs e)
    {
        if(e.AddedItems[0].ColumnName == "OrderID")
        {
            e.Cancel = true;
        }
    }

    Custom sorting

    The data grid allows sorting the columns based on custom logic when the standard sorting techniques do not meet the requirements. For each column, you can apply different sorting criteria by adding SortComparer objects to SfDataGrid.SortComparers collection.

    A SortComparer object has the following properties:

    • PropertyName: Gets mapping name of the column that applies custom sorting.
    • Comparer: Gets or sets the custom comparer that implements the IComparer and ISortDirection interfaces.

    The following code example illustrates how to perform custom sorting for FirstName column based on the string length of names:

  • c#
  • dataGrid.SortComparers.Add (new SortComparer () {
        PropertyName = "FirstName",
        Comparer = new CustomComparer()
    });
    
    dataGrid.SortColumnDescriptions.Add (new SortColumnDescription () {
        ColumnName = "FirstName",
        SortDirection = ListSortDirection.Descending
    });

    The following code example illustrates how to write a Custom Comparer.

  • c#
  • public class CustomComparer : IComparer<Object>, ISortDirection
    {
        public int Compare(object x, object y)
        {
            int nameX;
            int nameY;
    
            //For OrderInfo type data
            if (x.GetType () == typeof(OrderInfo)) {
                //Calculating the length of FirstName in OrderInfo objects
                nameX = ((OrderInfo)x).FirstName.Length;
                nameY = ((OrderInfo)y).FirstName.Length;
            }
    
            //For Group type data                                   
            else if (x.GetType () == typeof(Group)) {
                //Calculating the group key length
                nameX = ((Group)x).Key.ToString ().Length;
                nameY = ((Group)y).Key.ToString ().Length;
            } else {
                nameX = x.ToString ().Length;
                nameY = y.ToString ().Length;
            }
    
            // Objects are compared and return the SortDirection
            if (nameX.CompareTo (nameY) > 0)
                return SortDirection == ListSortDirection.Ascending ? 1 : -1;
            else if (nameX.CompareTo (nameY) == -1)
                return SortDirection == ListSortDirection.Ascending ? -1 : 1;
            else
                return 0; 
        }
    
        //Gets or sets the SortDirection value
        public ListSortDirection SortDirection { get; set; }
    }

    Animate sorting icons

    The data grid loads two different icons for denoting the ascending and descending sort direction states. However, the data grid allows rotating the DataGridStyle.GetHeaderSortIndicatorUp icon animatedly for denoting the descending state by overriding the DataGridStyle.GetHeaderSortIndicatorDown method and returning 0.

    The following code example illustrates how to enable the sorting icons animation by writing a custom style:

    //Apply custom style to SfDataGrid from code 
    
    dataGrid.GridStyle = new CustomStyle ();
    
    //Custom Style class
    
    public class CustomStyle : DataGridStyle
    { 
       public CustomStyle ()
       {
           
       }
       public override ImageSource GetHeaderSortIndicatorDown()
       {
           return 0;
       }
    }

    How to disable sorting for an individual column

    The data grid allows disabling sorting for an individual column by using the GridColumn.AllowSorting property. The default value of this property is true. Hence, all the columns in the SfDataGrid.Columns collection can be sorted when SfDataGrid.AllowSorting is set to true.

    The following code example illustrate how to disable sorting for an individual column:

    for auto generated column

  • c#
  • protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        dataGrid = new SfDataGrid(this);
        viewModel = new ViewModel();
        dataGrid.ItemsSource = viewModel.OrdersInfo;
        dataGrid.AllowSorting = true;
        dataGrid.AutoGeneratingColumn += DataGrid_AutoGeneratingColumn;
        SetContentView (dataGrid);
    }
            
    private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnEventArgs e)
    {
        // Sorting will not be done for the Freight column
        if (e.Column.MappingName == "Freight")
            e.Column.AllowSorting = false;
    }

    for manually defined column

  • c#
  • protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        dataGrid = new SfDataGrid(this);
        viewModel = new ViewModel();
        dataGrid.ItemsSource = viewModel.OrdersInfo;
        dataGrid.AutoGenerateColumns = false;
        dataGrid.AllowSorting = true;
        dataGrid.Columns.Add(new GridTextColumn() { MappingName = "OrderID" });
        // Sorting will not be done for the Freight column
        dataGrid.Columns.Add(new GridTextColumn() { MappingName = "Freight", AllowSorting = false });
        dataGrid.Columns.Add(new GridTextColumn() { MappingName = "Country" });
        SetContentView (dataGrid);         
    }