DataGridView中与时间列空值排序 [英] DataGridView sorting with nulls in DateTime column

查看:188
本文介绍了DataGridView中与时间列空值排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在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.

这篇关于DataGridView中与时间列空值排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆