首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >KeyPress字母和间距

KeyPress字母和间距
EN

Stack Overflow用户
提问于 2015-05-02 16:16:20
回答 2查看 348关注 0票数 0

下面是我的代码,用于验证我的文本框。目前,我只在Letter上使用它,但是我不知道如何允许空格。

代码语言:javascript
复制
Private Sub txtFirstname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtFirstname.KeyPress
    If Char.IsLetter(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
        MessageBox.Show("Letters only.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        ' Stop invalid character appearing in field
        e.KeyChar = Nothing
    End If
End Sub
EN

回答 2

Stack Overflow用户

发布于 2015-05-02 16:28:13

使用Char.IsWhiteSpace(e.KeyChar)方法

我还建议使用AndAlso而不是And运算符。

代码语言:javascript
复制
If Char.IsLetter(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then

操作员AndAlso避免多余的检查,如果第一个条件为负,则退出。

编辑

当你高效地实现函数时,应该看起来像这样。您还应该将它放在一个私有子例程中,并在KeyPress处理程序子例程中调用它。以便在要验证输入的每个事件中重用代码

代码语言:javascript
复制
Private Sub txtFirstname_KeyPress(ByVal sender As Object, ByVal e As     System.Windows.Forms.KeyPressEventArgs) Handles txtFirstname.KeyPress
    ValidateInput(e)
End Sub

Private Sub ValidateInput(e As EventArgs)
If Char.IsWhiteSpace(e.KeyChar) = False Then        
    If Char.IsLetter(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
                MessageBox.Show("Letters only.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
                ' Stop invalid character appearing in field
                e.KeyChar = Nothing
        End If
     End If
End Sub
票数 0
EN

Stack Overflow用户

发布于 2015-05-02 18:37:18

您可以使用以下命令检查:字母、数字和空格(Tab、空格和enter):

代码语言:javascript
复制
Private Sub textBox1_KeyPress(sender As Object, e As KeyPressEventArgs)
  e.Handled = True
  Dim IsLetter As Boolean = (e.KeyChar >= 65 AndAlso e.KeyChar <= 90) OrElse (e.KeyChar >= 97 AndAlso e.KeyChar <= 122)
  Dim IsNumber As Boolean = (e.KeyChar >= 48 AndAlso e.KeyChar <= 57)
  Dim IsWhiteSpace As Boolean = (e.KeyChar = 9) OrElse (e.KeyChar = 13) OrElse (e.KeyChar = 32)
  If IsLetter OrElse IsWhiteSpace OrElse IsNumber Then
    e.Handled = False
    MessageBox.Show("Just numbers and letters and whitespaces")
  End If
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29999994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档