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.
Sample Link:
C#: Sorting CS
VB: Sorting VB