我在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
但不知怎的,它不允许我输入字符。当我尝试输入任何角色时,它什么都不做。
导致此问题的原因是什么?如何解决?
答案 0 :(得分:8)
或者,你可以这样做,
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
两者的行为都相同。
答案 1 :(得分:0)
Private Sub txtname_KeyPress(ByVal sender As Object,ByVal e As System.Windows.Forms.KeyPressEventArgs)处理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
我希望这有帮助!
答案 2 :(得分:0)
这是一种更抽象的方法,但仍然有效。它很简单,可以添加到TextChanged
事件中。您可以将其句柄添加到子文件并使用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
摘要:如果输入的字符无效,则会立即将其删除(大多数情况下,该字符的显示时间不足以让用户注意)。
答案 3 :(得分:-1)
from escpos.printer import Serial
ser = Serial('COM3', 9600, timeout=1)
ser.text("Hello world\n")