选择案例陈述和数据验证

时间:2019-02-16 04:43:53

标签: vb.net visual-studio-2010 select-case

我正在尝试使用select case语句验证数据范围。我在其他嵌套选择案例中遇到了问题。这可能吗?还是应该分开要堆叠的select case语句?

例如,这是我在vb中的代码:

Select Case intyear
    Case 2000 To 2025
        Select Case intmonth
            Case 1 To 12
                BlnDateValid = True
        End Select
        Select Case intDay
            Case 1 To 31
                BlnDateValid = True
        End Select
        Select Case intHours
            Case 0 To 23
                BlnDateValid = True
        End Select
        Select Case intAddDays
            Case 0 To 60
                BlnDateValid = True
        End Select
        Select Case intAddHours
            Case 0 To 23
                BlnDateValid = True
        End Select
    Case Else
        BlnDateValid = False
End Select


If blnDatevalid = false then
    MessagebBox.Show("Please check all fields and enter valid 
data", "Invalid data", MessageBoxButtons.OK)

2 个答案:

答案 0 :(得分:0)

不幸的是,有意义的缩进并没有帮助代码变得有意义。 Select Case的重点是要巧妙地选择多种情况之一。带有大小写的Select Case是错误的代码,您应该改用If语句。在这种情况下,您尤其应该使用If语句,因为您可以用单个Select Case语句替换所有这些If语句。

If Not (intyear >= 2000 AndAlso intyear <= 2025 AndAlso
        intmonth >= 1 AndAlso intmonth <= 12 AndAlso
        intDay >= 1 AndAlso intDay <= 31 AndAlso
        intHours >= 0 AndAlso intHours <= 23 AndAlso
        intAddDays >= 0 AndAlso intAddDays <= 60 AndAlso
        intAddHours >= 0 AndAlso intAddHours <= 23) Then
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If

答案 1 :(得分:0)

所有SelectIf的检查仍将使您容易受到2月30日这样的无意义值的影响。最好尝试创建一个DateTime值。

Dim d As DateTime
Dim t As TimeSpan
Try
    d = New DateTime(intYear, intMonth, intDay, intHours, 0, 0)
    t = New TimeSpan(intAddDays, intAddHours, 0, 0)
    If t > (New TimeSpan(60, 23, 0, 0)) Then Throw New ArgumentOutOfRangeException() 
Catch
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End Try

或者您可以创建一个字符串并尝试对其进行解析:

If Not DateTime.TryParse($"{intYear}-{intMonth}-{intDay} {intHours}:00:00")
    MessagebBox.Show("Please check all fields and enter valid data", "Invalid data", MessageBoxButtons.OK)
End If