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
4

1 回答 1

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
于 2013-03-27T01:12:08.297 回答