Validate a textbox

时间:2015-09-01 21:17:32

标签: vb.net visual-studio

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 个答案:

答案 0 :(得分:2)

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