DataGridView 在 DateTime 列中使用空值进行排序 [英] DataGridView sorting with nulls in DateTime column

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

问题描述

我在 Windows 窗体应用程序中有一个 DataGridView 控件.有四列包含字符串数据,三列包含日期时间数据.我正在使用 Rows.Add() 方法以编程方式添加行.所有列都将 SortMode 设置为 Automatic.单击列标题进行排序是有效的,但有一些空值的 DateTime 列除外.当用户单击该列的标题时,它会抛出一个 ArgumentException: Object must be of type 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代码.我假设每个单元格值都是 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 在 DateTime 列中使用空值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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