获取文本框以仅接受vb.net中的字符 [英] Get a textbox to accept only characters in vb.net
本文介绍了获取文本框以仅接受vb.net中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在Vb.net中创建一个简单的应用程序,需要执行某些验证.因此,我希望名称文本框仅接受a-z和A-Z中的字符.
I'm creating a simple application in Vb.net where I need to perform certain validations. So I want a name textbox to accept only characters from a-z and A-Z for example.
为此,我编写了以下代码:
For this I wrote the following code:
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
但是以某种方式不允许我输入字符.当我尝试输入任何字符时,它什么都不做.
But somehow it is not allowing me to enter characters. When I try to enter any character it does nothing.
什么原因导致此问题,我该如何解决?
What causes this problem and how can I resolve it?
推荐答案
或者,您可以执行类似的操作
Alternatively, you can do something like this,
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
方式,请尝试此操作
or if you still want the ASCII
way, try this,
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
两者的行为相同.
这篇关于获取文本框以仅接受vb.net中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文