Articles in this section
Category / Section

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

2 mins read

This KB article clearly explains on how to implement the custom IComparer to sort a column in the WinForms GridControl.

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

 

Conclusion

I hope you enjoyed learning about how to implement the custom IComparer to sort a column in the WinForms GridControl.

You can refer to our WinForms GridControl feature tour page to know about its other groundbreaking feature representations. You can also explore our WinForms GridControl documentation to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

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