Reputation: 25
I have a DateTimePicker
that will restrict the user from selecting weekends, but I am not sure how to limit the picker to only certain hours of the day as well. I have tried using .AddHours(12)
but that could put the time at 4-5am which is outside of the window I'm trying to adhere to.
I'm trying to limit the selection between 8a-4p local time.
Any assistance would be appreciated.
Private Sub DateTimePick_CloseUp(ByVal sender As Object, ByVal e As System.EventArgs) Handles DateTimePick.ValueChanged
If (DateTimePick.Value.DayOfWeek = DayOfWeek.Saturday) Or (DateTimePick.Value.DayOfWeek = DayOfWeek.Sunday) Then
'Now just add the right amount of days to make it Monday
Select Case DateTimePick.Value.DayOfWeek
Case DayOfWeek.Saturday
DateTimePick.Value = DateTimePick.Value.AddDays(2)
Case DayOfWeek.Sunday
DateTimePick.Value = DateTimePick.Value.AddDays(1)
End Select
MsgBox("We're sorry, we are not currently scheduling maintenance for Saturday or Sunday. The following Monday, " &
DateTimePick.Value.ToShortDateString & ", has been selected.",
MsgBoxStyle.Exclamation, "Invalid selection")
End If
End Sub
Upvotes: 2
Views: 454
Reputation: 54417
If you want to automatically move weekends to the next Monday and invalid times to the nearest valid time on the same day, handle the Leave
event and do this:
Private Sub DateTimePicker1_Leave(sender As Object, e As EventArgs) Handles DateTimePicker1.Leave
Dim dt = DateTimePicker1.Value
Select Case dt.DayOfWeek
Case DayOfWeek.Saturday
dt = dt.AddDays(2)
Case DayOfWeek.Sunday
dt = dt.AddDays(1)
End Select
If dt.TimeOfDay < TimeSpan.FromHours(8) Then
dt = dt.Date.AddHours(8)
ElseIf dt.TimeOfDay > TimeSpan.FromHours(16) Then
dt = dt.Date.AddHours(16)
End If
DateTimePicker1.Value = dt
End Sub
If you want to force the user to select a valid date and time themselves, handle the Validating
event and do this:
Private Sub DateTimePicker1_Validating(sender As Object, e As CancelEventArgs) Handles DateTimePicker1.Validating
Dim dt = DateTimePicker1.Value
If dt.DayOfWeek = DayOfWeek.Saturday OrElse
dt.DayOfWeek = DayOfWeek.Sunday OrElse
dt.TimeOfDay < TimeSpan.FromHours(8) OrElse
dt.TimeOfDay > TimeSpan.FromHours(16) Then
MessageBox.Show("Please select a time between 8:00 AM and 4:00 PM on a weekday",
"Invalid Date/Time",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation)
e.Cancel = True
End If
End Sub
Upvotes: 2