Validate a textbox

2019-09-01 08:20发布

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

1条回答
闹够了就滚
2楼-- · 2019-09-01 08:47

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
查看更多
登录 后发表回答