vb.net 如何在visual basic中验证文本框中的数字范围数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20134383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate number range array in textbox in visual basic?
提问by PatrickGamboa
So basically in a form, you have 3 textboxes and each of them you can input a number, then you have a button that check if each of these textboxes are in a range of numbers specified. It's very much like a lock combo, but I need help checking values, for example;

所以基本上在一个表单中,你有 3 个文本框,每个文本框都可以输入一个数字,然后你有一个按钮来检查这些文本框中的每一个是否在指定的数字范围内。它非常像一个锁定组合,但我需要帮助检查值,例如;

the only thing i can figure out is
我唯一能弄清楚的是
Dim intOne As Integer
Dim intTwo As Integer
Dim intThree As Integer
Dim blnInputOk As Boolean = True
If Integer.TryParse(lblOne.Text, intOne) = False Then
MessageBox.Show("Value must be an integer")
blnInputOk = False
End If
If Integer.TryParse(lblTwo.Text, intTwo) = False Then
MessageBox.Show("Value must be an integer")
blnInputOk = False
End If
If Integer.TryParse(lblThree.Text, intThree) = False Then
MessageBox.Show("Value must be an integer")
blnInputOk = False
End If
If intOne >= 6 And intOne <= 8 Then
If intTwo >= 2 And intOne <= 9 Then
If intThree >= 0 And intThree <= 8 Then
MessageBox.Show("Good code!")
Else
MessageBox.Show("Wrong, number must be between range 0 to 8")
End If
Else
MessageBox.Show("Wrong, number must be between range 2 to 9")
End If
Else
MessageBox.Show("Wrong, number must be between range 6 to 8")
End If
So my question is how can you make this code simpler by adding an array for number range for each textbox? I also know there is a possibility of adding a loop, but i'm not sure how to structure it, can anyone help? thanks
所以我的问题是如何通过为每个文本框添加一个数字范围数组来简化此代码?我也知道有可能添加一个循环,但我不确定如何构建它,有人可以帮忙吗?谢谢
回答by ArBR
There are many ways, all depends on the number of values you are going to compare, the simplest is by adding a comparison function.
有很多方法,都取决于您要比较的值的数量,最简单的是添加比较函数。
Private Function IsInRange(x As Integer, a As Integer, b As Integer) As Boolean
Dim r As Boolean
r = (x >= a And x <= b)
If r Then
MessageBox.Show("Good code!")
Else
MessageBox.Show(String.Format("Wrong, number {0} must be between range {1} to {2}", x, a, b))
End If
Return r
End Function
Then according to the code shown in your question, you can do this:
然后根据您的问题中显示的代码,您可以执行以下操作:
If IsInRange(intOne, 6, 8) Then
If IsInRange(intTwo, 2, 9) Then
IsInRange(intThree, 0, 8)
End If
End If

