vb.net - 获取文本框以仅接受 vb.net 中的字符

我正在 Vb.net 中创建一个简单的应用程序,我需要在其中执行某些验证。所以我想要一个名称文本框只接受来自 a-z 和 A-Z 的字符。

为此我写了下面的代码:

   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

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

导致此问题的原因是什么,我该如何解决?

最佳答案

或者,你可以这样做,

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

两者的行为相同。

https://stackoverflow.com/questions/12633780/

相关文章:

c# - 从 AJAX 发布的字符串中删除 BOM 字符

parsing - 关于如何实现 BASIC 语言解析器/解释器的任何建议?

php - 如何使用 php 获取 URL 主机

arrays - MIPS中的冒泡排序算法

sql - DB2 中的意外标记 "LIMIT"

python - 我如何将参数传递给鼠兔回调

jsp - 如何从 jsp 页面获取选定行的列表或选定复选框的列表到 liferay 6 中 por

Vb.net - 仅在单击项目时显示上下文菜单条

sql-server-2008 - 在 SQL 查询中对日期时间列使用通配符

visual-studio-2010 - 当我尝试在 VS 2010 中运行 Nuint 测试时,此