Reputation: 1
The code is just asking for the pass rates for 6 different colleges. The rate must be a value between 1 and 100.
I would like it to only allow numbers. I have tried using IsNumeric
, but I must not be using it correctly. Here's what I have so far:
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
Upvotes: 0
Views: 9882
Reputation: 105
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
This will allow only positive Decimal numbers using the ASCII Table, you should be able to modify this for your own use
Upvotes: 0
Reputation: 2152
I see a couple of things to note.
To avoid that conversion you could use a simple RegEx. This one will validate it to be an integer between 1 and 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
Admitily RegEx can be a bit much... So here is another way to check that the input string will cast to an integer and if so is it between 1 and 100 in value.
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
You can call either of these like so:
Dim validInput as Boolean = False
While Not validInput
validInput = IsValid(InputBox("Enter the pass rate for " & colleges(i) & " college")
Loop
Upvotes: 0
Reputation: 5307
use this function for check value
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
and use like this
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
Upvotes: 1