我在入门级视觉基础课。我试图测试用户输入,看看它是否使用IsNumeric布尔函数进行数字化。基本上,如果输入不是数字,我希望它抛出一个消息框这样说,如果它是数字,我希望它将数值设置为变量。每次输入非数字值时,我都没有得到消息框,而是在尝试使用CDbl将非数字字符串转换为double时出现异常。我做错了什么?
If txtInches.Text = "" Or txtFeet.Text = "" Then 'Checks to ensure height fields were not left blank
'If fields were blank, throws error message up, changes textbox backgroud color to red, focuses user on error and exits sub.
MessageBox.Show("You must enter a value for both feet and inches. Don't leave these fields blank, and try again.", "Height Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtInches.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf txtAge.Text = "" Then 'Checks to see if age field was blank
'If age field was blank, throws error message up, changes textbox backgroud color to red, focuses user on error and exits sub.
MessageBox.Show("You must enter your age. Don't leave this field blank, and try again.", "Age Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtInches.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf Not IsNumeric(dblFeet) Then
'If feet input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Feet must be a numeric value. Please try again.", "Height Error", MessageBoxButtons.OK)
txtFeet.BackColor = Color.Red
txtFeet.Focus()
Exit Sub
ElseIf Not IsNumeric(dblInches) Then 'Checks to see if height input is numeric
'If inches input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Inches must be a numeric value. Please try again.", "Height Error", MessageBoxButtons.OK)
txtInches.BackColor = Color.Red
txtInches.Focus()
Exit Sub
ElseIf Not IsNumeric(dblAge) Then 'Checks to see if age input is numeric
'If age input is not numeric, throws error message up, changes textbox background color to red, focuses user on error and exits sub.
MessageBox.Show("Your age must be a number. Please try again.", "Age Error", MessageBoxButtons.OK)
txtAge.BackColor = Color.Red
txtAge.Focus()
Exit Sub
Else
dblFeet = CDbl(txtFeet.Text)
dblInches = CDbl(txtInches.Text)
dblAge = CDbl(txtAge.Text)
End If
答案 0 :(得分:0)
哦,我明白了。当我应该测试txtVariable.text时,我正在测试dblVariable。捂脸。
答案 1 :(得分:0)
假设您对教育感兴趣,而不仅仅是一个年级,这里使用NET方法更为简洁:
' assumes all the values are form/class
' leval variables
Private nAge As Int32
然后进行验证:
' if it parses, then nAge will have the value
If Integer.TryParse(tbAge.Text, nAge) = False Then
MessageBox.Show("Please enter a valid integer for Age",
"Annoying MsgBox", MessageBoxButtons.OK)
Return
End If
"5.8"
英尺或输入"28.7"
年龄?Integer.TryParse
您只能执行一项测试:它会检测/失败空字符串以及"I like pie"
ErrorProvider
对此有好处。旧VB函数的一个问题是几乎所有东西都是As Object
。这允许您执行类似IsNumeric(dblAge)
的操作,这将永远是真的。 NET方法的类型更强,因此您只能传递一个字符串。