【问题标题】:How to validate number range array in textbox in visual basic?如何在 Visual Basic 的文本框中验证数字范围数组?
【发布时间】:2013-11-21 23:57:19
【问题描述】:

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

我唯一能想到的是

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

所以我的问题是如何通过为每个文本框添加一个数字范围数组来简化此代码?我也知道有可能添加一个循环,但我不知道如何构建它,有人可以帮忙吗?谢谢

【问题讨论】:

  • 如下所述,NumericUpDown() 控件就是为此而设计的,因为您可以指定 Minimum() 和 Maximum() 值。 Value() 将始终在该范围内,并保证为整数。
  • @Idle_Mind 实际上,NumericUpDown 使用Decimal 类型(最小值、最大值、值和增量都是十进制)。 DecimalPlaces 属性默认为 0,因此很容易认为它是 Integer,但它不是。
  • @Plutonix,非常正确。它实际上是一个具有默认设置的“整数”。

标签: arrays vb.net visual-studio-2010 loops


【解决方案1】:

有很多方法,都取决于你要比较的值的数量,最简单的是添加一个比较函数。

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

那么根据你问题中显示的代码,你可以这样做:

If IsInRange(intOne, 6, 8) Then
    If IsInRange(intTwo, 2, 9) Then
        IsInRange(intThree, 0, 8)
    End If
End If

【讨论】:

  • 哇,第二个可能真的有帮助!您显示的第二个代码是数组吗?如果我可以将范围值存储在数组中,那真的很有帮助,是否可以使用数字范围显示您的代码? (例如第一个,下限为 6,上限为 8)
【解决方案2】:

.NET 在标准输入控件上具有输入验证功能。 Here's 一个不错的起点。

【讨论】:

  • 另外,对于整数,您也可以使用 NumericUpDown。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多