Sorting

This section explains you about Sorting on SfDataGrid data. Different properties and events that participate in Sorting are discussed in this section.

Overview

SfDataGrid control allows you to sort the table data against one or more columns. The number of columns by which the data sorted is unlimited. When sorting is applied, the SfDataGrid rearranges the data to match with the current sort criteria ascending or descending order.

SfDataGrid provides following properties for Sorting.

Property Type Description Default Value
SfDataGrid.AllowSorting Boolean Enables or disables a value to AllowSorting property indicating whether the SfDataGrid is resorted by clicking on a column header. True
SfDataGrid.SortColumnDescriptions ObservableCollection < SortColumnDescription > Columns that are added to this collection are allowed to be sorted.
SfDataGrid.AllowTristateSorting Boolean Enables or disables tristate sorting for a SfDataGrid. (Ascending, descending and initial data order.) False
SfDataGrid.ShowSortNumbers Boolean You can get the order of sorting in columns header during multi sorting. False
GridColumn.AllowSorting Boolean Enables or disables a value to AllowSorting property indicating whether the GridColumn is resorted by clicking on a column header. True

NOTE

When SfDataGrid.AllowSorting property is set to’ true’, GridColumn.AllowSorting property gets more priorities to sort the columns.

Apply Sorting

There is a couple of ways to apply sorting to the SfDataGrid.

  • You can click the column header by which the column is sorted. Once the sorting is applied, the SfDataGrid shows a sort icon in the respective column headers indicating the direction of sorting.
  • You can also perform sorting using the code. This requires you to define a number of SortColumnDescription objects to be added to SfDataGrid.SortColumnDescriptions collection. SortColumnDescription object holds following two properties:
    • ColumnName: Name of the sorted column
    • SortDirection: an object of type ListSortDirection defines the soring direction

The following code example illustrates this.

<syncfusion:SfDataGrid x:Name="datagrid"

                       AllowSorting="True"

                       ColumnSizer="Auto"

                       ItemsSource="{Binding OrderInfoCollection}">

    <syncfusion:SfDataGrid.SortColumnDescriptions>

        <syncfusion:SortColumnDescription ColumnName="OrderID" SortDirection="Descending" />

    </syncfusion:SfDataGrid.SortColumnDescriptions>

</syncfusion:SfDataGrid>
dataGrid.AllowSorting = true;



dataGrid.SortColumnDescriptions.Add(new SortColumnDescription() { ColumnName = "OrderID", SortDirection = System.ComponentModel.ListSortDirection.Descending });

The following screenshot displays the output.

Events

The SfDataGrid provides you the following Events for the sorting functionality:

  • SfDataGrid.SortColumnChanging: This Event is raised while sorting the column in code or at Execute time that helps to cancel the sorting action. When you sort the column, SfDataGrid scrolls based on Selected Item. By setting SortColumnChangingEventArgs.CancelScroll property to ‘true’, you can prevent the scrolling while sorting.
  • SfDataGrid.SortColumnChanged: This Event is raised after the column is sorted.

The following code example explains you how to hook those events.

<syncfusion:SfDataGrid x:Name="dataGrid"

                       AllowSorting="True"

                       AutoGenerateColumns="True"

                       ColumnSizer="Star"

                       ItemsSource="{Binding OrderInfoCollection,

                                                Source={StaticResource data}}"

                       SortColumnsChanged="dataGrid_SortColumnsChanged"

                       SortColumnsChanging="dataGrid_SortColumnsChanging" />
dataGrid.SortColumnsChanging += dataGrid_SortColumnsChanging;

dataGrid.SortColumnsChanged += dataGrid_SortColumnsChanged;



void dataGrid_SortColumnsChanged(object sender, GridSortColumnsChangedEventArgs e)

{            

}



void dataGrid_SortColumnsChanging(object sender, GridSortColumnsChangingEventArgs e)

{

}

Tristate Sorting

By default SfDataGrid allows you to sort the column in ascending and descending order only. SfDataGrid.AllowTristateSorting allows you to sort the column in the following three orders:

  • Ascending order
  • Descending order
  • Initial data order

The following code example illustrates that.

  • xaml
  • <syncfusion:SfDataGrid x:Name="dataGrid"
    
                           AllowSorting="True"
    
                           AllowTriStateSorting="True"
    
                           AutoGenerateColumns="True"
    
                           ColumnSizer="Star"
    
                           ItemsSource="{Binding OrderInfoCollection,
    
                                                    Source={StaticResource data}}" />

    Multi Column Sorting

    SfDataGrid control allows you to sort the multiple columns. To apply sorting for multiple columns, you can click the desired column headers by pressing the CTRL key.

    The following screenshot illustrates the MultiColumnSorting in SfDataGrid.

    In the above screenshot, “OrderID” column is sorted first in the descending order. After you sort the “Name of Customer”, the sorting of column in any direction happens against OrderID column and previous sorting is maintained.

    NOTE

    When you add columns to SortColumnDescription, SortColumnChanging event is not raised.

    Sort Numbers

    SfDataGrid.ShowSortNumbers property enables the visibility of sorting order of the column at the top right corner of Column HeaderCell.

    The following code example illustrates that.

  • xaml
  • <syncfusion:SfDataGrid x:Name="dataGrid"
    
                           AllowSorting="True"
    
                           AutoGenerateColumns="True"
    
                           ColumnSizer="Star"
    
                           ItemsSource="{Binding OrderInfoCollection,
    
                                                    Source={StaticResource data}}"
    
                           ShowSortNumbers="True" />

    The following screenshot illustrates the SortNumbers in SfDataGrid.

    In the above screenshot SfDataGrid shows the sort order numbers in column header. OrderId column is sorted first in ascending order. Then you can apply multi sort to CustomerName and CustomerID column. Now the SfDataGrid shows sort numbers in column header, based on column sorting order.

    Sort groups based on summary

    When you group data by any column, the records are grouped by identical values of the particular column. By default, each grouped record sorted by column’s key value is shown in the following screenshot.

    Now you can sort the grouped records based on key values of the column. You can sort the records based on Caption Summary value that is achieved by using SummaryGroupComparer property in SfDataGrid.

    Following are the steps to create comparer to sort the record based on Caption Summary value of the group,

    • Create the Comparer class by implementing two interfaces IComparer to compare the summary values of two groups and ISortDirection that has the SortDirection property.
    • In compare method, get the summary values of two groups by GetSummaryValue method and return the compared result based on SortDirection property (member of ISortDirection interface).

    The following code example illustrates how to create a GroupComparer class that sorts the grouped records based on Count Aggregate.

  • c#
  • public class SummaryGroupComparer : IComparer<Group>, ISortDirection
    
    {
    
        public ListSortDirection SortDirection { get; set; }
    
        public int Compare(Group x, Group y)
    
        {
    
            int compare = 0;
    
            var xGroupSummary = Convert.ToInt32((x as Group).GetSummaryValue(x.SummaryDetails.SummaryRow.SummaryColumns[0].MappingName, "Count"));
    
            var yGroupSummary = Convert.ToInt32((y as Group).GetSummaryValue(x.SummaryDetails.SummaryRow.SummaryColumns[0].MappingName, "Count"));
    
            compare = ((IComparable)xGroupSummary).CompareTo(yGroupSummary);
    
            if (this.SortDirection == ListSortDirection.Descending)
    
                compare = -compare;
    
            return compare;
    
        }
    
    }

    Group Comparer class is assigned to SummaryGroupComparer property of SfDataGrid. This is attained by defining the class as a Resource.

  • xaml
  • <Page.Resources>
    
        <local:SummaryGroupComparer x:Key="groupComparer" />
    
    </Page.Resources>
    
    <Grid>
    
        <syncfusion:SfDataGrid x:Name="syncgrid"
    
                               AutoGenerateColumns="True"
    
                               ColumnSizer="Star"
    
                               ItemsSource="{Binding EmployeeDetails}"
    
                               ShowColumnWhenGrouped="True"
    
                               ShowGroupDropArea="True"
    
                               SummaryGroupComparer="{StaticResource groupComparer}">
    
            <syncfusion:SfDataGrid.CaptionSummaryRow>
    
                <syncfusion:GridSummaryRow Title="Items Count: {IdCount}" ShowSummaryInRow="True">
    
                    <syncfusion:GridSummaryRow.SummaryColumns>
    
                        <syncfusion:GridSummaryColumn Name="IdCount"
    
                                                      Format="'{Count}'"
    
                                                      MappingName="CustomerID"
    
                                                      SummaryType="CountAggregate" />
    
                    </syncfusion:GridSummaryRow.SummaryColumns>
    
                </syncfusion:GridSummaryRow>
    
            </syncfusion:SfDataGrid.CaptionSummaryRow>
    
        </syncfusion:SfDataGrid>
    
    </Grid>

    Now the group rows are automatically sorted by their summary values. You can sort group rows by summary values by clicking the grouped column header.

    The above screenshot shows the output for sort by summary value example.

    Custom Sorting

    Custom Sorting feature enables you to implement custom sorting criteria. For each column, you can apply different sorting criteria. To perform the custom sorting you have to add SortComparer object to SfDataGrid.SortComparersCollection.

    A SortComparer object has the following properties:

    • PropertyName: Gets or sets the column Mapping Name that applies custom sorting.
    • Comparer: Gets or sets the custom comparer. CustomComparer implements the IComparer and ISortDirection interfaces.

    In the following example, the column is sorted based on string.Length by using custom comparer. The following code example illustrates how to perform the custom sorting for Customer Name column according to the string length of the names.

  • xaml
  • <Page.Resources>
    
            <local:OrderInfoRepositiory x:Key="data" />
    
            <local:CustomerInfo x:Key="Comparer" />
    
        </Page.Resources>
    
        <syncfusion:SfDataGrid x:Name="dataGrid"
    
                               AllowSorting="True"
    
                               AllowTriStateSorting="True"
    
                               AutoGenerateColumns="True"
    
                               ColumnSizer="Star"
    
                               ItemsSource="{Binding OrderInfoCollection,
    
                                                     Source={StaticResource data}}"
    
                               ShowGroupDropArea="True"
    
                               ShowSortNumbers="True">
    
            <syncfusion:SfDataGrid.SortComparers>
    
                <Linq:SortComparer Comparer="{StaticResource Comparer}" PropertyName="CustomerName" />
    
            </syncfusion:SfDataGrid.SortComparers>
    
        </syncfusion:SfDataGrid>
    
    </Page>

    The following code example illustrates the Custom Comparer.

  • c#
  • public class CustomerInfo : IComparer<Object>, ISortDirection
    
    {
         public int Compare(object x, object y)
         {
              int nameX;
              int nameY;
    
            //For Customers Type data
    
            if (x.GetType() == typeof(Customers))
            {
    
            //Calculating the length of CustomerName if the object type is Customers
                nameX = ((Customers)x).CustomerName.Length;
                nameY = ((Customers)y). CustomerName.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; 
    
         }
    
         //Get or Set the SortDirection value
         private ListSortDirection _SortDirection;
         public ListSortDirection SortDirection
         {
         get  {   return _SortDirection;  }
         set  {  _SortDirection = value;    }
         }
    
    }

    The following screenshot displays the output

    In the preceding screenshot, Name of Customer column is sorted based on string.Length value.