How to custom sort a string column so that all the empty cells in the WinForms GridGroupingControl?
Custom sorting
Description
By default, empty cells are included while sorting in the WinForms GridGroupingControl.
To keep these empty cells always at the bottom while sorting, you have to
implement an IComparer interface.
Solution
This customized sorting can be done by having a user-defined class that
implements the IComparer interface and writing the custom
comparer code in the Compare method. Excluding the empty cells can
be done by finding the length of the string in the Compare method
and cancelling its sorting, thereby pushing the empty cells to the bottom.
Refer to the following code to implement the Compare method.
C#
public class customsort : IComparer
{
public int Compare(object x, object y)
{
if(x == null && y == null)
return 0;
// Does not include empty strings for comparison.
else if (x == System.DBNull.Value)
{
return 0;
}
else if (y == System.DBNull.Value)
{
return 0;
}
else
{
return ((IComparable)x.ToString()).CompareTo(y.ToString());
}
}
}
VB
Public Class customsort Implements IComparer
Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer
If x Is Nothing AndAlso y Is Nothing Then
Return 0
'Does not include empty strings for comparison.
ElseIf x Is System.DBNull.Value Then
Return 0
ElseIf y Is System.DBNull.Value Then
Return 0
Else
Return (CType(x.ToString(), IComparable)).CompareTo(y.ToString())
End If
End Function
You can create an instance of the SortColumnDescriptor for a particular column and set the Comparer method to the instance of the inherited IComparer class. You can also initialize its sorting direction by using the Sort Direction property.
C#
//Sets the columnname to be sorted.
SortColumnDescriptor cd = new Syncfusion.Grouping.SortColumnDescriptor("City");
this.gridGroupingControl1.TableDescriptor.SortedColumns.Add(cd);
//Sets the sortdirection.
cd.SortDirection = System.ComponentModel.ListSortDirection.Descending;
//Handles the empty cells at the bottom.
cd.Comparer = new customsort();
VB
'Sets the columnname to be sorted.
Dim cd As SortColumnDescriptor = New Syncfusion.Grouping.SortColumnDescriptor("City")
Me.gridGroupingControl1.TableDescriptor.SortedColumns.Add(cd)
'Sets the sortdirection.
cd.SortDirection = System.ComponentModel.ListSortDirection.Descending
'Handles the empty cells at the bottom.
cd.Comparer = New customsort()
Samples:
C#: Custom sorting
VB: Custom sorting
Reference Link: Custom Sorting