2

我正在 Vb.net 中创建一个简单的应用程序,我需要在其中执行某些验证。因此,我希望名称文本框仅接受来自 az 和 AZ 的字符。

为此,我编写了以下代码:

   Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress
    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) > 65 Or Asc(e.KeyChar) < 90 Or Asc(e.KeyChar) > 96 Or Asc(e.KeyChar) < 122 Then
            e.Handled = True
        End If
    End If
End Sub

但不知何故,它不允许我输入字符。当我尝试输入任何字符时,它什么也不做。

是什么导致了这个问题,我该如何解决?

4

4 回答 4

11

或者,你可以做这样的事情,

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

    If Not (Asc(e.KeyChar) = 8) Then
        Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz"
        If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If

End Sub

或者如果你仍然想要这ASCII条路,试试这个,

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

    If Not (Asc(e.KeyChar) = 8) Then
        If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then
            e.KeyChar = ChrW(0)
            e.Handled = True
        End If
    End If

End Sub

两者的行为相同。

于 2012-09-28T04:55:26.920 回答
0
Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress

    If AscW(e.KeyChar) > 64 And AscW(e.KeyChar) < 91 Or AscW(e.KeyChar) > 96 And AscW(e.KeyChar) < 123 Or AscW(e.KeyChar) = 8 Then 
    Else
        e.KeyChar = Nothing
    End If

End Sub

我希望这有帮助!

于 2013-10-06T15:27:30.303 回答
0

这是一种更抽象的方法,但仍然有效。它很简单,可以添加到TextChanged事件中。您可以通过将它们的句柄添加到 sub 并使用DirectCast().

Dim allowed As String = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
        For Each c As Char In TextBox.Text
            If allowed.Contains(c) = False Then
                TextBox.Text = TextBox.Text.Remove(TextBox.SelectionStart - 1, 1)
                TextBox.Select(TextBox.Text.Count, 0)
            End If
        Next

摘要:如果输入了无效字符,它将立即被删除(大多数情况下,该字符的可见时间不足以让用户注意到)。

于 2015-08-01T04:14:01.593 回答
-1
Private Sub txtStudentName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtStudentName.KeyPress

  If Not Char.IsLetter(e.KeyChar) And Not e.KeyChar = Chr(Keys.Delete) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Space) Then

      e.Handled = True

  End If

End Sub
于 2017-05-27T04:54:59.233 回答