DataGridView sorting with nulls in DateTime column

前端 未结 5 1243
猫巷女王i
猫巷女王i 2021-01-14 04:30

I\'ve got a DataGridView control in a Windows forms application. There are four columns with string data and three with DateTime data. I\'m adding the rows programmatically

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-14 04:58

    Here's the solution I came up with. The DataGridView raises a SortCompare event that you can use to input custom sorting. I'm handling that event and making null values sort out higher than non-null values (you could just as easily make nulls lower than non-nulls). Here's the VB code. I'm assuming every cell value is IComparable (if not it will be handled by the normal error handling logic.)

    Try
        If e.CellValue1 Is Nothing OrElse e.CellValue1.Equals(DBNull.Value) Then
            If e.CellValue2 Is Nothing OrElse e.CellValue2.Equals(DBNull.Value) Then
                e.SortResult = 0
            Else
                e.SortResult = 1
            End If
        Else
            If e.CellValue2 Is Nothing OrElse e.CellValue2.Equals(DBNull.Value) Then
                e.SortResult = -1
            Else
                e.SortResult = DirectCast(e.CellValue1, IComparable).CompareTo(DirectCast(e.CellValue2, IComparable))
            End If
        End If
        e.Handled = True
    Catch ex As Exception
        HandleError("Error sorting result grid values", ex)
        Close()
    End Try
    

    If anybody has any improvements on this please feel free to post them.

提交回复
热议问题