【问题标题】:Sorting a DataGridView by date column using a custom IComparer使用自定义 IComparer 按日期列对 DataGridView 进行排序
【发布时间】:2016-08-05 20:39:38
【问题描述】:

我在带有日期列的表单上有一个数据网格视图,我想在按下排序按钮时对该列进行排序。

这里是按钮点击事件的代码:

Private Sub DateOfBirthSortButton_Click(sender As Object, e As EventArgs) Handles DateOfBirthSortButton.Click
    PatientDataGridView.Sort(New DatabaseModule.DateComparer)
End Sub

对于比较器:

Public outputFile As String = "C:\Users\Patrick\Desktop\outputTest.txt"

Public Class DateComparer
    Implements IComparer

    ' Compare the two dates
    Public Function Compare(ByVal rowX As Object, ByVal rowY As Object) As Integer Implements System.Collections.IComparer.Compare

        'Get the date value from the collection of cells in the row
        Dim dateX As String = rowX.Cells.Item(2).Value.ToString
        Dim dateY As String = rowX.Cells.Item(2).Value.ToString

        'Convert to a date
        Dim x As Date = DateTime.ParseExact(dateX, "dd-MM-yyyy", Nothing)
        Dim y As Date = DateTime.ParseExact(dateX, "dd-MM-yyyy", Nothing)

        'Compare
        Dim cmpDate As Integer = Date.Compare(x, y)

        Dim objWriter As New System.IO.StreamWriter(outputFile, True)

        objWriter.WriteLine(dateX & " " & dateY & " " & cmpDate)
        objWriter.Close()

        Return cmpDate

    End Function
End Class

我添加了将比较器的结果放入文本文件的代码,以便我可以看到每次比较的结果。

但是,当按下按钮时,比较器只会将同一行与自身进行比较,以看似随机的顺序,有时会多次。

这是最初的顺序(我已经给出了人员编号以显示他们应该按哪个顺序排序):

以及按下排序按钮后的结果顺序:

以及记录在文本文件中的比较:

如果有人能向我解释如何解决我的问题,我将不胜感激,谢谢:)

【问题讨论】:

  • 数据是如何进入 DGV 的?它完全能够自行排序日期

标签: .net vb.net sorting


【解决方案1】:

简短的回答是你有一个复制粘贴错误:

Dim dateX As String = rowX.Cells.Item(2).Value.ToString
'  note that DateY is also getting from RowX
'   should be         rowY
Dim dateY As String = rowX.Cells.Item(2).Value.ToString

您还应该打开Option StrictrowXrowY 被传递为Object,但您将它们用作DataGridViewRows 而没有强制转换它们:

Public Function Compare(X As Object, Y As Object) ...
    Dim rowX = TryCast(X, DataGridViewRow)

如果/当您确实需要自定义排序器时,您可能希望编写它以允许构造函数中的列和排序顺序,以便它可以处理多个列,并且能够从升序翻转到降序并返回。示例:

' specify the column to sort, and the order:
dgv1.Sort(New DGVPatientSorter(2, thisOrder))

由于它允许您使用排序器,因此不能绑定数据。太糟糕了。但是,如果您将该列定义为 Date 类型,它将很好地对日期进行排序:

dgv1.Columns(2).ValueType = GetType(DateTime)

然后排序:

dgv1.Sort(dgv1.Columns(2), ListSortDirection.Ascending)

【讨论】:

  • 如果你告诉 DGV 它是一个日期列,你真的不需要它
  • 那我该怎么做呢?我浏览了列集合的属性,但找不到选项。
  • 答案是 - 由于某种原因,您无法在列设计器中执行此操作。 dgv1.Columns(2).ValueType = GetType(DateTime)
  • 啊,抱歉,还没有完整阅读您的答案 :D 感谢您的帮助,现在可以正常工作了 :)
  • 如果设置为DateTime,仍然保留排序器,可以使用DirectCast代替parse
猜你喜欢
  • 2012-12-22
  • 2010-11-02
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2022-10-23
  • 2019-09-28
  • 2020-07-31
  • 2015-09-25
相关资源
最近更新 更多