该代码只是要求6个不同学院的通过率。费率必须介于1到100之间。
我希望它只允许数字。我尝试过使用IsNumeric
,但我一定不能正确使用它。这是我到目前为止所做的:
For i As Integer = 0 To 5
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
While passRate(i) > 100 Or passRate(i) < 0
MsgBox("Error must be a number and be between 0 and 100")
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
End While
Next i
答案 0 :(得分:0)
将此功能用于检查值
Private Function IsInputNumeric(input As String) As Boolean
If String.IsNullOrWhiteSpace(input) Then Return False
If IsNumeric(input) Then Return True
Dim parts() As String = input.Split("/"c)
If parts.Length <> 2 Then Return False
Return IsNumeric(parts(0)) AndAlso IsNumeric(parts(1))
End Function
并像这样使用
For i As Integer = 0 To 5
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
If IsInputNumeric(passRate(i)) Then
'handle numeric input
Else
'handle not a number
End If
While passRate(i) > 100 Or passRate(i) < 0
MsgBox("Error must be a number and be between 0 and 100")
passRate(i) = InputBox("Enter the pass rate for " & colleges(i) & " college")
End While
答案 1 :(得分:0)
我看到了一些需要注意的事项。
为了避免这种转换,您可以使用简单的RegEx。这个将验证它是1到100之间的整数:
Function IsValid(Byval inputString as String) as Boolean
Dim validValues As New Regex("^[1-9]?[0-9]{1}$|^100$")
Return validValues.IsMatch(inputString )
End Function
遗憾的是,RegEx可能有点多......所以这是检查输入字符串是否会转换为整数的另一种方法,如果是这样,它的值是1到100之间。
Function IsValid(Byval inputString as String) as Boolean
Dim result As Boolean = False
Dim inputAsInteger as Integer = 0
If Integer.TryParse(value, inputAsInteger) Then
result = inputAsInteger > 0 And inputAsInteger <= 100)
End If
Return result
End Function
你可以这样打电话:
Dim validInput as Boolean = False
While Not validInput
validInput = IsValid(InputBox("Enter the pass rate for " & colleges(i) & " college")
Loop
答案 2 :(得分:0)
Private Sub txbDwellTime_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbDwellTime.KeyPress
pNumDecOnly(e)
'txbDwellTime.Text = ""
End Sub
Public Sub pNumDecOnly(ByVal e As System.Windows.Forms.KeyPressEventArgs)
If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 46) Then
'good job do nothing we only allow positive Decimal numbers in this field
'Asc(e.KeyChar) 48 Through 57 i.e. 0 through 9 Or Asc(e.KeyChar) 46 (dot= .)
Else
e.Handled = True
MsgBox("Only Positive Decimal Numbers Allowed this field")
End If
End Sub
这将只允许使用ASCII表的正十进制数,您应该可以对其进行修改以供自己使用