簡體   English   中英

如何在Visual Basic中驗證文本框中的數字范圍數組?

[英]How to validate number range array in textbox in visual basic?

因此,基本上在一個表單中,您有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

所以我的問題是,如何通過為每個文本框的數字范圍添加數組來簡化此代碼? 我也知道有可能添加一個循環,但是我不確定如何構造它,有人可以幫忙嗎? 謝謝

有很多方法,所有方法都取決於您要比較的值的數量,最簡單的方法是添加比較功能。

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

.NET在標准輸入控件上具有輸入驗證功能。 這是一個不錯的起點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM