我目前有3个文本框。每个文本框都必须包含一个数字。如果三个文本框中的任何一个不包含数字值,则显示错误消息。对于不显示数字的文本框(IsNumeric返回false),我想更改其默认值。我该怎么做?
If Not (IsNumeric(txtpadult.Text)) Or Not (IsNumeric(txtpjunior.Text)) Or Not (IsNumeric(txtpconc.Text)) Then
MsgBox("ERROR: INVALID NUMERIC !", vbCritical, "System Message")
End if
提前致谢。
答案 0 :(得分:4)
首先,我建议尽可能使用新的.NET方法,而不是采用旧的VB6样式方法。因此,我建议使用MsgBox
代替MessageBox.Show
而不是IsNumeric
,而不是Integer.TryParse
,我会使用Dim invalid As TextBox = Nothing
If Not Integer.TryParse(txtpadult.Text, 0) Then
invalid = txtpadult
ElseIf Not Integer.TryParse(txtpjunior.Text, 0) Then
invalid = txtpjunior
ElseIf Not Integer.TryParse(txtpconc.Text, 0) Then
invalid = txtpconc
End If
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If
等。
因此,例如,您可以像这样重写代码:
invalid
正如您所看到的,当它测试每个文本框时,如果找到一个无效的文本框,它会在Dim textBoxes() As TextBox = {txtpadult, txtpadult, txtpconc}
Dim invalid As TextBox = Nothing
For Each i As TextBox In textBoxes
If Not Integer.TryParse(i.Text, 0) Then
invalid = i
Exit For
End If
Next
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If
变量中保留对它的引用。然后它可以检查是否找到了一个并设置了它的值。或者,您可以创建一个需要检查的文本框列表,然后循环遍历它们,如下所示:
Dim textBoxes() As TextBox = {txtpadult, txtpadult, txtpconc}
Dim invalid As TextBox = textBoxes.FirstOrDefault(Function(x) Not Integer.TryParse(x.Text, 0))
If invalid IsNot Nothing Then
MessageBox.Show("ERROR: INVALID NUMERIC !", "System Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
invalid.Text = "0" ' Set to default value
End If
或者,如果你想要聪明,你可以使用LINQ扩展方法在更少的代码行中完成:
{{1}}