2013-03-27 193 views
0

我的问题是,我试图让用户只能输入“a,b,c或d”。如果他们没有输入这四个字母中的一个,而只是用户只能输入这些字母,我宁愿让它出错。我只能找到与数字数据类似的资源(使用try catch)。任何网站或提示将是伟大的。验证字符串用户输入

   If String.Compare(TextBox2.Text, "a", True) = 0 AndAlso String.Compare(TextBox21.Text, "a", True) = 0 Then 
       'MessageBox.Show("A") 
       totCorrect = totCorrect + corAns 
      ElseIf String.Compare(TextBox2.Text, "b", True) = 0 AndAlso String.Compare(TextBox21.Text, "b", True) = 0 Then 
       'MessageBox.Show("B") 
       totCorrect = totCorrect + corAns 
      ElseIf String.Compare(TextBox2.Text, "c", True) = 0 AndAlso String.Compare(TextBox21.Text, "c", True) = 0 Then 
       'MessageBox.Show("C") 
       totCorrect = totCorrect + corAns 
      ElseIf String.Compare(TextBox2.Text, "d", True) = 0 AndAlso String.Compare(TextBox21.Text, "d", True) = 0 Then 
       'MessageBox.Show("D") 
       totCorrect = totCorrect + corAns 
      Else 
       totWrong = totWrong + wrgAns 
       Label13.Visible = True 
      End If 
+0

愚蠢的问题,但如果你希望用户只选择A,B,C或d,为什么不使用组合框代替文本框?那么你将不必做所有这些检查... – 2013-03-27 01:06:42

回答

1

这应该做的伎俩

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress 

    Dim allowableChar As New List(Of Char) From {"a"c, "b"c, "c"c, "d"c} 

    Call allowableChar.AddRange(allowableChar.Select(Function(c) Convert.ToChar(c.ToString().ToUpper())).ToList()) 

    If Not (allowableChar.Contains(e.KeyChar) OrElse e.KeyChar = Convert.ToChar(Keys.Delete) OrElse e.KeyChar = Convert.ToChar(Keys.Back)) Then 
     e.Handled = True 
    End If 

End Sub 

Call allowableChar.AddRange(...)增加了大写字母的名单。就像现在一样,这会在每次执行方法时生成一个新列表,这有点浪费......如果你使用这段代码,我建议你将可允许的字符列表作为一个类级变量并仅填充它一次在你的表单的构造函数中。

要只允许一次每种类型的字符,使用此:

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress 

    Dim allowableChar As New List(Of Char) From {"a"c, "b"c, "c"c, "d"c} 

    Call allowableChar.AddRange(allowableChar.Select(Function(c) Convert.ToChar(c.ToString().ToUpper())).ToList()) 

    If Not (allowableChar.Contains(e.KeyChar) OrElse e.KeyChar = Convert.ToChar(Keys.Delete) OrElse e.KeyChar = Convert.ToChar(Keys.Back)) Then 
     e.Handled = True 
    Else 
     If Me.TextBox1.Text.Count(Function(c) c = e.KeyChar) >= 1 Then 
      e.Handled = True 
     End If 
    End If 

End Sub 
+0

这将工作......我可能会拉伸一般的代码可以做但是,你认为它可能只允许1“a”或1 “b”等? – Brandon 2013-03-27 01:21:42

+0

当然,我更改了代码以包含该代码,但如果您确实想要这样做,则可以使用一组复选框而不是文本框。除非输入字母的顺序很重要。 – 2013-03-27 01:26:10