【发布时间】:2017-01-24 20:51:43
【问题描述】:
我正在尝试验证输入以仅接受 1-100 的数字范围。我有它,它将接受 1-100 范围内的数字。我需要的是如何确保不能使用诸如字母或符号(?、/、 等)之类的字符输入。我正在使用循环来查看放入数组中的每个输入。验证输入后,我将返回一个 blnOk = True 以在我的按钮事件中使用以运行程序。我试过 double.TryParse 但我无法让它与数组一起工作。我也有 Option Strict ON。 dblStudentTestScores(i) 是存储输入的数组。txtTestScores(i) 数组用于告诉程序循环在哪个文本框上,以便在出错时获得焦点。
Private Sub ValidateScores()
For i = 0 To 8
If dblStudentTestScores(i) >= 0 And dblStudentTestScores(i) <= 100 Then
blnOK = True
Else
MessageBox.Show("Please Enter Test Score between 0 and 100")
txtTestScores(i).Clear()
txtTestScores(i).Focus()
txtTestScores(i).BackColor = Color.Yellow
blnOK = False
Exit Sub
End If
txtTestScores(i).BackColor = Color.White
Next
blnOK = True
End Sub
这是带有 IsNumeric 的代码,但它不会进入 Else 子句。它跳入try catch。我真的希望它能够专注于具有无效输入的文本框。就像数字不在 0 到 100 之间一样。
Private Sub ValidateScores()
For i = 0 To 8
If CInt(IsNumeric(dblStudentTestScores(i))) >= 0 And CInt(IsNumeric(dblStudentTestScores(i))) <= 100 Then
blnOK = True
Else
MessageBox.Show("Please Enter Test Score between 0 and 100")
txtTestScores(i).Clear()
txtTestScores(i).Focus()
txtTestScores(i).BackColor = Color.Yellow
blnOK = False
Exit Sub
End If
txtTestScores(i).BackColor = Color.White
Next
blnOK = True
End Sub
每个输入都填充数组。
Public Sub PopulateTestScores()
'Student 1 test scores
dblStudentTestScores(0) = CDbl(txtStudent1Score1.Text)
dblStudentTestScores(1) = CDbl(txtStudent1Score2.Text)
dblStudentTestScores(2) = CDbl(txtStudent1Score3.Text)
'Student 2 test scores
dblStudentTestScores(3) = CDbl(txtStudent2Score1.Text)
dblStudentTestScores(4) = CDbl(txtStudent2Score2.Text)
dblStudentTestScores(5) = CDbl(txtStudent2Score3.Text)
'Student 3 test scores
dblStudentTestScores(6) = CDbl(txtStudent3Score1.Text)
dblStudentTestScores(7) = CDbl(txtStudent3Score2.Text)
dblStudentTestScores(8) = CDbl(txtStudent3Score3.Text)
End Sub
【问题讨论】:
-
这段代码有什么问题?这是验证测试,但我看不到你在哪里输入并检查它们是否真的是数字。
-
它仍然允许我输入诸如 ?,/,>,' 之类的字符,甚至允许输入字母。我只需要被允许在输入中使用数字。在这一点上,我唯一要做的验证就是检查输入是否在 0 到 100 之间。
-
您应该使用 double.TryParse 来检查输入是否有效。你能展示将双打添加到数组中的代码吗?
-
另外,你说你有 Option Strict On 所以我假设你的数组 dblStudentTestScores 是一个双数组。对吗?
-
输入是双精度的。
标签: arrays vb.net visual-studio validation