验证文本框 [英] Validate a textbox
问题描述
我使用的是visual basic 2010,我有一个文本框,我需要验证它才能接受十进制数,我该如何添加代码?我有这个代码只用于整数
I'm using visual basic 2010 and I have a textbox and I need to validate it to also accept decimal number how can I add the code? I have this code just for integer
If Not ( (e.KeyValue >= 48 And e.KeyValue <= 57)
OrElse (e.KeyValue >= 96 And e.KeyValue <= 105)
OrElse (e.KeyValue = 8) ) Then
e.Handled = True
MsgBox("Este campo requiere únicamente valores númericos")
AngulobuzamientoTextBox.Text = vbNullChar
End If
推荐答案
与其尝试在输入时一次一个验证 TextBox 中的字符,我建议等到用户完成输入并将焦点移至另一个控件.然后您可以处理 TextBox 的 Validating 事件并使用 Decimal.TryParse
来验证文本并将其转换为十进制值.如果验证失败,则显示错误消息并设置 e.Cancel = True
以防止焦点移出 TextBox.
Rather than try to validate the characters in the TextBox one at a time as they are typed, I suggest waiting until the user finishes typing and moves focus to another control. Then you can handle the TextBox's Validating event and use Decimal.TryParse
to validate the text and convert it to a decimal value. If the validation fails, show an error message and set e.Cancel = True
to prevent the focus moving out of the TextBox.
Private number As Decimal
Private Sub TextBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If Not Decimal.TryParse(TextBox1.Text, number) Then
MessageBox.Show("Enter a valid Decimal Number")
e.Cancel = True
End If
End Sub
这篇关于验证文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!