0

I have a datagridview databound string column that contain string numbers 0-99 and blank, nothing.

I wish to sort this column numerically 0 to 99 with either the blank nothing cells at the beginning or at the end.

I use DataGridView_ColumnHeaderMouseClick event and check the column index to get the right one and then use an IComparer to sort.

Class Colomn5Comparer : Implements IComparer
    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        Dim XX As DataGridViewRow = DirectCast(x, DataGridViewRow)
        Dim YY As DataGridViewRow = DirectCast(y, DataGridViewRow)
        If Not XX.Cells(5).Value = "" AndAlso Not YY.Cells(5).Value = "" Then

            If CInt(XX.Cells(5).Value) < CInt(YY.Cells(5).Value) Then

                If m_SortOrder = "Desc" Then
                    Return 1
                Else
                    Return -1
                End If

            ElseIf CInt(XX.Cells(5).Value) > CInt(YY.Cells(5).Value) Then

                If m_SortOrder = "Desc" Then
                    Return -1
                Else
                    Return 1
                End If

            Else
                Return 0
            End If

        Else
            Return 0
        End If

    End Function
End Class

I've had to excluded the cells with nothing blank values to prevent the greater or less then integer comparison from erroring

 If Not XX.Cells(5).Value = "" AndAlso Not YY.Cells(5).Value = "" Then   

This of course leaves the blank nothing cells in their current row positions after sorting.

Is there a way I can include the nothing blank cells somehow in the sort so that they appear either at the bottom or the top of the sorted rows?

Mark
  • 1,360
  • 3
  • 20
  • 37

2 Answers2

0

Just found an answer, when excluding the blank values if I return -1 they will sort to the beginning.

Mark
  • 1,360
  • 3
  • 20
  • 37
0

some variation of this will give you more

If XX.Cells(5).Value = "" AndAlso  YY.Cells(5).Value = "" Then return 0;
If XX.Cells(5).Value = ""  Then return -1;
If YY.Cells(5).Value = ""  Then return +1;
paparazzo
  • 44,497
  • 23
  • 105
  • 176