We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: November 16, 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to implement the custom IComparer to sort a column in the GridControl?

Platform: WinForms |
Control: GridControl |
Published Date: April 30, 2011 |
Last Revised Date: May 28, 2019
Tags: sorting

Solution

The GridData's sortbycolumn method accepts an IComparer object. You can pass your custom IComparer to this method. The following code example sorts the 4th column by string length.

C#

this.gridControl1.Data.SortByColumn(col,(ListSortDirection)this.gridControl1[0, col].Tag, new StrLenComparer());

 

VB

Me.gridControl1.Data.SortByColumn(col,CType(Me.gridControl1(0, col).Tag, ListSortDirection), New StrLenComparer())

 

Refer to the following code example for custom IComparer method.

 

C#

public class StrLenComparer : IComparer
{
   // Implementation of IComparer
   public int Compare(object x, object y)
   {
 if(x == null && y == null)
    return 0;
 else if(x == null)
    return 1;
 else if(y == null)
    return -1;
 else
 {
   if(x.ToString().Length  > y.ToString().Length)
  return -1;
   if(x.ToString().Length  < y.ToString().Length)
  return 1;
   else
  return 0;
 }
    }
}

 

VB

Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
     If x Is Nothing AndAlso y Is Nothing Then
         Return 0
     ElseIf x Is Nothing Then
         Return 1
     ElseIf y Is Nothing Then
         Return -1
     Else
         If x.ToString().Length > y.ToString().Length Then
             Return -1
         End If
         If x.ToString().Length < y.ToString().Length Then
             Return 1
         Else
              Return 0
          End If
     End If
End Function

The following screenshot illustrates the CustomSort IComparer applied to the Text column.

Showing sort the column in GridControl

 

Sample Link:

C#: Sorting CS

VB: Sorting VB

 

2X faster development

The ultimate WinForms UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon