我有一个数组,该数组以字符串格式“ 10:00”存储时间,cboTime组合框显示了数组的内容。
我想验证选择的时间,我不想让用户从cboTime中选择已经在系统时钟中经过的时间。
但是,我没有得到想要的结果,并且代码没有按照应有的方式运行,我也不知道为什么。
请参见下面的代码,我对解决此问题非常满意。
Public strTimeRoomsEvents() As String = {"10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00"}
cboTime.DataSource = strTimeRoomsEvents
If dtpBookDate.Value > Today Then
valid_time = True
ElseIf dtpBookDate.Value = Today And DateTime.Now.ToShortDateString < cboTime.SelectedItem Then
valid_time = False
Else
valid_time = True
End If
答案 0 :(得分:1)
使用字符串作为时间和日期的问题之一是字符串可能会根据计算机设置的不同而不同,因此最好避免使用“ ToShortDateString”之类的东西,除非它们被用于显示数据。
我假设您要在更改日期或时间时检查有效性,并且您不希望早于今天的日期有效。另一个问题是在DateTime.Now.ToShortDateString < cboTime.SelectedItem
子句中-换个角度来看一下,然后考虑要比较的是什么。
我将您提到的控件放在窗体和标签上以显示状态:
Public Class Form1
Private Sub InitBookingTimes(startHour As Integer, endHour As Integer)
Dim startTimes = Enumerable.Range(startHour, endHour - startHour + 1).Select(Function(h) $"{h:00}:00").ToList()
cboTime.DataSource = startTimes
End Sub
Private Sub dtpBookDate_ValueChanged(sender As Object, e As EventArgs) Handles dtpBookDate.ValueChanged
Label1.Text = IsValidBookingTime(dtpBookDate, cboTime).ToString()
End Sub
Private Sub cboTime_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboTime.SelectedIndexChanged
Label1.Text = IsValidBookingTime(dtpBookDate, cboTime).ToString()
End Sub
Function IsValidBookingTime(dateSource As DateTimePicker, timeSource As ComboBox) As Boolean
Dim rightNow = DateTime.Now
Dim validTime = True
Dim proposedDate = dateSource.Value.Date
If proposedDate <= rightNow.Date Then
Dim proposedTime As TimeSpan
If TimeSpan.TryParse(CStr(timeSource.SelectedValue), proposedTime) Then
Dim proposedDateTime = proposedDate.Add(proposedTime)
validTime = proposedDateTime > rightNow
Else
' Could not parse time portion, so assume it is invalid
validTime = False
End If
End If
Return validTime
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitBookingTimes(10, 17)
End Sub
End Class
将对控件的引用传递到IsValidBookingTime
函数的目的是,您可以将相同的函数与其他控件一起使用,例如您可能要使用一对控件来完成预订时间。