下面是我的代码,用于验证我的文本框。目前,我只在Letter上使用它,但是我不知道如何允许空格。
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发布于 2015-05-02 16:28:13
使用Char.IsWhiteSpace(e.KeyChar)方法
我还建议使用AndAlso而不是And运算符。
If Char.IsLetter(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False Then操作员AndAlso避免多余的检查,如果第一个条件为负,则退出。
编辑
当你高效地实现函数时,应该看起来像这样。您还应该将它放在一个私有子例程中,并在KeyPress处理程序子例程中调用它。以便在要验证输入的每个事件中重用代码
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发布于 2015-05-02 18:37:18
您可以使用以下命令检查:字母、数字和空格(Tab、空格和enter):
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 Subhttps://stackoverflow.com/questions/29999994
复制相似问题