[英]Data Type validation in textbox
Trying to make a validation where only letters can be entered into a textbox.尝试进行验证,其中只能在文本框中输入字母。 I've got that part working, but I would also like the ability for the user to use the backspace button, and I'm not sure how我已经让那部分工作了,但我也希望用户能够使用退格按钮,但我不确定如何
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
If Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122 Then 'Ensures only letters can be entered by using the ASCII converter'
e.Handled = True
MessageBox.Show("You may only input letters")
End If
End Sub
Input validation is a built-in feature of .NET
.输入验证是.NET
的内置功能。 You don't need to capture key presses and manually code your own solution.您无需捕获按键操作并手动编写您自己的解决方案。
You might want to use a MaskedTextBox
as suggested in this article:您可能希望按照本文的建议使用MaskedTextBox
:
https://docs.microsoft.com/en-us/dotnet/framework/winforms/user-input-validation-in-windows-forms https://docs.microsoft.com/en-us/dotnet/framework/winforms/user-input-validation-in-windows-forms
You can change your If
statement like this:您可以像这样更改If
语句:
If (Asc(e.KeyChar) < 65 Or Asc(e.KeyChar) > 122) And Asc(e.KeyChar) <> 8 Then
Ascii 8 is the Backspace key. Ascii 8 是退格键。
Rather than using the KeyPress event, use the TextChanged event.使用TextChanged事件,而不是使用 KeyPress 事件。 Also, I would recommend using the IsNumeric function to test whether it is a number or not.另外,我建议使用IsNumeric函数来测试它是否是数字。
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As EventArgs) Handles TxtBoxCustForename.TextChanged
For Each entry as Char in TxtBoxCustForename.Text
If IsNumeric(entry) Then
MessageBox.Show("You may only input letters")
Exit For
End If
Next
End Sub
If you're going to use .NET then use .NET.如果您要使用 .NET,请使用 .NET。
Private Sub TxtBoxCustForename_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtBoxCustForename.KeyPress
Dim keyChar = e.KeyChar
If Not Char.IsLetter(keyChar) AndAlso Not Char.IsControl(keyChar) Then
e.Handled = True
MessageBox.Show("You may only input letters")
End If
End Sub
This still doesn;t prevent the user pasting invalid text into the control though, so you still need to handle the Validating
event or use a custom control that catches paste operations.这仍然不能阻止用户将无效文本粘贴到控件中,因此您仍然需要处理Validating
事件或使用捕获粘贴操作的自定义控件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.