使用特定字母在文本框中输入验证

时间:2016-08-07 17:17:09

标签: .net vb.net

我试图将您可以在5个文本框中使用的字母限制为“D,H,C和S”

我的代码是:

suit(0) = txtSuit1.Text
suit(1) = txtSuit2.Text
suit(2) = txtSuit3.Text
suit(3) = txtSuit4.Text
suit(4) = txtSuit5.Text


    For i As Integer = 0 To 4
        If suit(i) <> "D" And suit(i) <> "H" And suit(i) <> "C" And suit(i) <> "S" And suit(i) = "" Then
            MessageBox.Show("Choose a suit using D for Diamonds, H for Hearts, C for Clubs or S for Spades")
        End If
    Next'

即使我输入随机字母,消息框也不会显示。使用Or代替And会使消息框每次都弹出。

如果该框为空白,则在此代码中抛出一个消息框也存在问题:

            cards(0) = CInt(txtCard1.Text)
            cards(1) = CInt(txtCard2.Text)
            cards(2) = CInt(txtCard3.Text)
            cards(3) = CInt(txtCard4.Text)
            cards(4) = CInt(txtCard5.Text)



    For i As Integer = 0 To 4
        If cards(i) > 13 Or cards(i) < 1 Or Not IsNumeric(cards(i)) Or cards(i) = "" Then
            MessageBox.Show("Enter a number between 1-13")
        End If
    Next'

每次有空白框时,我都会收到一条错误,说明输入“整数”字符串“”无效。 当文本框留空时,如何抛出消息框?

1 个答案:

答案 0 :(得分:1)

通常最好是防止用户输入错误的数据,而不是编写代码来骂他们。为此,请使用ComboBox代表套装,使用NumericUpDown作为卡片等级。

否则,验证收集内容的简单代码:

' suit is your string array of suit letters
Dim suitCodes = {"H", "C", "D", "S"}

Dim bValid As Boolean = True
For Each s As String In suit
    If suitCodes.Contains(s) = False Then
        ' optionally save 's' and report it as bad
        bValid = False
    End If
Next
If bValid = False Then
    MessageBox.Show("Please enter only 'H, C, S, D' for suits")
End If

如果我必须这样做,我通常会收集所有错误值并将其报告给用户而不是通用消息。但是,永远不要将MessageBox放在循环中 - 它们只需要告诉一次,告诉一次,告诉一次。

最初可以为数字做同样的事情,但你必须允许他们输入文字而不是数字。使用TryParse而不是CINT

' cards is a bad var name
Dim ranks(4) As Int32

If Integer.TryParse(TextBox1.Text, ranks(0)) Then
    If ranks(0) < 1 OrElse ranks(0) > 13 Then bValid = False
Else
    bValid = False
End If

但是你有一个更大的问题迫在眉睫。在大多数情况下,Aces很高但你似乎将它们存储为1(Lo)。你不希望一对三分球看起来击败一对A,所以你应该转换它们:

Dim temp As Int32
If Integer.TryParse(TextBox1.Text, temp) Then
    If temp > 0 AndAlso temp < 14 Then
        If temp = 1 Then
            ' store Ace as Hi:
            ranks(0) = 14
        Else
            ranks(0) = temp
        End If
    End If
Else
    bValid = False
End If

或者,让他们输入2-14的值。