Xceed Grid for WinForms v4.3 Documentation
Custom Sorting
Welcome to Xceed Grid for WinForms v4.3 > Advanced Concepts > Custom Sorting

Although Xceed Grid for WinForms allows for columns to be sorted, by default, in an ascending or descending direction, it is also possible to provide custom sorting definitions through the use of data comparers.

Data comparers

Any class that implements the IComparer interface can be used by Xceed Grid for WinForms to custom sort columns. To assign a data comparer to a column, the column's DataComparer property must be set. This data comparer will then be used when sorting the column to which it was assigned. For example:

C# Copy Code
gridControl1.Columns[ "ShipAddress" ].DataComparer = new AddressComparer();

In the example above, we use the AddressComparer class (which is provided below) to compare the values of the ShipAddress column. The AddressComparer class will first sort addresses which begin with numeric values by street name and then civic number. The remainder of the addresses in the regular alphabetical fashion. For example, if we were to use the default data comparer for the ShipAddress column, the result would be something like : 

Using the AddressComparer data comparer class, the result would be: 

AddressComparer class

C# Copy Code

using System;
using System.Collections; 

namespace Xceed.Grid.Samples;
{
  public class AddressComparer : IComparer
  {
    public AddressComparer()
             
    

    int IComparer.Compare( object x, object y )
    {
      if( x is string && y is string   )
      {
        const string digits = "0123456789";        

         if( ( digits.IndexOf( ( ( string )x )[ 0 ] ) >= 0 ) &&
          ( digits.IndexOf( ( ( string )y )[ 0 ] ) >= 0 ) )
        {
          int index = 0;
          System.Text.StringBuilder xNumber = new System.Text.StringBuilder(); 

           while( ( index < ( ( string )x ).Length ) &&
                 ( digits.IndexOf( ( ( string )x )[ index ] ) >= 0 ) )
          {
             xNumber.Append( ( ( string )x )[ index ] );
             index++;
          

           index = 0;
          System.Text.StringBuilder yNumber = new System.Text.StringBuilder(); 

           while( ( index < ( ( string )y ).Length )&&
                 ( digits.IndexOf( ( ( string )y )[ index ] ) >= 0  ) )
          {
             yNumber.Append( ( ( string )y )[ index ] );
             index++;
           }          

           long xValue = long.Parse( xNumber.ToString() );
          long yValue = long.Parse( yNumber.ToString() ); 

           if( xValue > yValue )
             return 1;

           if( xValue < yValue )
             return -1;          

           return ( ( string )x ).CompareTo( ( string )y );
        }
        else
        {
          return ( ( string )x ).CompareTo( ( string )y );
        }
      }

      throw new ArgumentException( "Can only compare string values" );
    }
  }
}