我在带有日期列的表单上有一个数据网格视图,我想在按下排序按钮时对列进行排序。
以下是按钮点击事件的代码:
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
我添加了代码,将比较器的结果放入文本文件中,以便我可以看到每次比较的结果。
然而,当按下按钮时,比较器仅以相似的随机顺序(有时多次)将同一行与自身进行比较。
这是最初的订单(我已经给出了人员编号,以显示他们应该排序的订单):
按下排序按钮后的结果顺序:
比较记录在文本文件中:
如果有人能向我解释如何解决我的问题,我将非常感激,谢谢:)
答案 0 :(得分: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 Strict
,rowX
和rowY
作为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)
然后排序:
import sys,os
PATHTOFILE1="Some_path"
PATHTOFILE2="some other path"
os.environ['PATHTOFILE1'] = PATHTOFILE1
os.environ['PATHTOFILE2'] = PATHTOFILE2
os.system('xcopy "$PATHTOFILE1" "$PATHTOFILE2" /s /y /q >nul')