简体   繁体   中英

VB .Net IComparer sorting string that include blanks numerically

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?

刚刚找到答案,当排除空值时,如果我返回-1,它们将排序到开头。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM