DateTimePicker:限制一天中的时间

时间:2020-06-22 15:56:05

标签: vb.net datetimepicker

我有一个DateTimePicker,它将限制用户选择周末,但是我不确定如何将选择器也限制为一天中的某些小时。我曾尝试使用.AddHours(12),但这可能会使时间凌晨4点至5点,这超出了我要遵守的范围。 我试图将选择范围限制在当地时间8a-4p之间。 任何帮助将不胜感激。

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

1 个答案:

答案 0 :(得分:2)

如果您想自动将周末移至下周一,并将无效时间移至同一天的最近有效时间,请处理Leave事件并执行以下操作:

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

如果要强制用户自己选择有效的日期和时间,请处理Validating事件并执行以下操作:

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