New to Telerik UI for WinFormsStart a free 30-day trial

Mixing default and custom sorting in multisort scenario

Updated over 6 months ago
Product VersionProductAuthorLast modified
Q3 2012 SP1RadControls for WinFormsStefan Stefanov25 Dec 2012

Problem

This example shows how to use both the default and custom sorting to sort your grid. In the below grid all columns prior Column2 are sorted with the default sort mechanism, while for Column2 itself, we will use custom sorting.

Solution

To achieve this, all you need to do is to set the EnableCustomSorting property of RadGridView to true and implement the desired sorting logic in the CustomSorting event handler, while keeping the default sorting for the rest of the cases:

C#
void radGridView1_CustomSorting(object sender, Telerik.WinControls.UI.GridViewCustomSortingEventArgs e)
{
    //sort all descriptors before 'column2' are using the default comparer
    SortDescriptorCollection descriptors = e.Template.SortDescriptors;
    int index = descriptors.IndexOf("Column2");
    if (index > 0)
    {
        SortDescriptorCollection context = new SortDescriptorCollection();
        for (int i = 0; i < index; i++)
        {
            context.Add(descriptors[i]);
        }
 
        e.SortResult = GridViewRowInfoComparer.CompareRows(e.Row1, e.Row2, context);
    }
 
    if (e.SortResult == 0 && index >= 0)
    {
        decimal value1 = (decimal)e.Row1.Cells["Column2"].Value;
        decimal value2 = (decimal)e.Row2.Cells["Column2"].Value;
        e.SortResult = decimal.Compare(value1, value2);
        if (e.SortResult != 0)
        {
            if (descriptors[index].Direction == System.ComponentModel.ListSortDirection.Descending)
            {
                e.SortResult *= -1;
            }
 
            return;
        }
    }
 
    //default sorting
    e.Handled = false;
}
In this article
ProblemSolution
Not finding the help you need?
Contact Support