Articles in this section
Category / Section

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

2 mins read

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

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied