【发布时间】: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 的?它完全能够自行排序日期