DataGridView中与时间列空值排序中与、时间、DataGridView、列空值

由网友(怀中山河.)分享简介:我有在Windows DataGridView控件窗体应用程序。有四列字符串数据和三连DateTime数据。我添加以编程方式使用Rows.Add()方法的行。所有的列有SortMode设置为自动。单击列标题进行排序只是工程,除了一个DateTime列有一些空值。当用户点击该列的标题,它抛出一个ArgumentExcep...

我有在Windows DataGridView控件窗体应用程序。有四列字符串数据和三连DateTime数据。我添加以编程方式使用Rows.Add()方法的行。所有的列有SortMode设置为自动。单击列标题进行排序只是工程,除了一个DateTime列有一些空值。当用户点击该列的标题,它抛出一个ArgumentException:对象必须是DateTime类型

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 using the Rows.Add() method. All of the columns have SortMode set to Automatic. Clicking the column headers to sort just works, except for the one DateTime column that has some nulls. When the user clicks that column's header, it throws an ArgumentException: Object must be of type DateTime.

我知道硬盘的方式来解决这个问题:将所有的SortModes到NotSortable的,处理ColumnHeaderMouseClick事件和人工分拣整个事情。我正在寻找最简单的方式。

I know the hard way to get around this: setting all of the SortModes to NotSortable, handling the ColumnHeaderMouseClick event and sorting the whole thing manually. I'm looking for the easy way.

有一个属性或东西我可以设置,或其他一些相对简单的方法,让此列在它空值排序?

Is there a property or something I can set, or some other relatively simple way to allow this column to sort with nulls in it?

推荐答案

下面是我想出了一个解决方案。在DataGridView提出了SortCompare事件,您可以使用输入自定义排序。我在处理该事件,使空值理清比非空值较高(你可以很轻松地进行比非空值较低的空值)。这里的VB code。我假定每个单元格的值是IComparable的(如果不是由正常的错误处理逻辑进行处理。)

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.

阅读全文

相关推荐

最新文章