下面是我的代码,用于验证我的文本框。目前我只为Letters工作,但我也不知道如何允许间距。
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
答案 0 :(得分:0)
使用方法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
答案 1 :(得分:0)
您可以使用以下方式检查:字母,数字和空格(制表符,空格和输入):
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