Sorting is an important feature for any Grid control. C1FlexGrid for WinForms also supports sorting along with the capability to customize this feature as per the user requirement. For example, sorting a particular CellRange in C1FlexGrid has already been discussed here.

In this blog, we discuss yet another utility implementation of Sorting in C1Flexgrid. There might be certain scenario where sorting is required on the basis of non empty cells in a Column. This blog deals with the implementation where rows with blank cells in the column (on which sorting will be applied) is moved downwards and sorting is performed on the rest of the non empty cells.

The approach is as follows:

  1. Create an object of C1FlexGrid and fill data in it.

  2. Capture the C1FlexGrid's BeforeSort event to remove the blanks rows

  3. Capture the C1FlexGrid's AfterSort event and append these blank rows at the bottom.


Please note, this implementation targets only the Unbound C1FlexGrid. You may fill the grid through code or directly input the values into the cell.

Isolating Rows with non empty cells


Once the data has been entered in the C1FlexGrid, we need to get the collection of all the rows having any blank cell with respect to the column on which the sorting has to be applied. In order to get the same we can use the 'Clip' property of the Row object. As we add the data fetched from theses rows (having blank cells) to the array, we remove them from C1FlexGrid.



Dim blankCell As List(Of String) = New List(Of String)()
Private Sub C1FlexGrid1_BeforeSort(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.SortColEventArgs) Handles C1FlexGrid1.BeforeSort
Dim j As Integer = (C1FlexGrid1.Rows.Count - 1)
Do While (j > 0)
If ((C1FlexGrid1(j, e.Col) Is Nothing) OrElse (C1FlexGrid1(j, e.Col).ToString = "")) Then
Dim rw As C1.Win.C1FlexGrid.Row = C1FlexGrid1.Rows(j)
blankCell.Add(C1FlexGrid1.GetCellRange(j, 0, j, 2).Clip)
C1FlexGrid1.Rows.Remove(rw)
End If
j = (j - 1)
Loop
End Sub

Append removed row data at the end of Row Collection


After the grid has been sorted, data for the rows which were removed are appended back into the grid.


Private Sub C1FlexGrid1_AfterSort(ByVal sender As Object, ByVal e As C1.Win.C1FlexGrid.SortColEventArgs) Handles C1FlexGrid1.AfterSort
If (blankCell.Count > 0) Then
Dim j As Integer = (blankCell.Count - 1)
Do While (j >= 0)
Dim newString() As String = System.Text.RegularExpressions.Regex.Split(blankCell(j), "" & vbTab)
C1FlexGrid1.AddItem(New String() {newString(0), newString(1).ToString, newString(2).ToString})
j = (j - 1)
Loop
blankCell.Clear()
End If
End Sub


Following images show the C1FlexGrid appearance for the above sorting implementation:

Non-Sorted Grid :


Sorted Grid - Ascending :


Sorted Grid - Descending :


Download the attached samples for complete implementation.
Download Sample-C#
Download Sample-VB