Check whether the text entered in a text box is decimal or not

The sample VB.NET code is used to check if the value in a text box is decimal or not. This code can be written in textbox keypress event



Private Sub numericTextboxKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) ' Handles TextBox1.KeyPress, TextBox2.KeyPress
Dim chr As Char = e.KeyChar
If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
e.Handled = Not IsNumeric(sender.Text & e.KeyChar)
ElseIf e.KeyChar = "." Then
If Not (sender.SelectedText = "." Or IsNumeric(sender.Text & e.KeyChar)) Then
e.Handled = True
End If
ElseIf e.KeyChar = "-" Then
If sender.SelectionStart <> 0 Or Microsoft.VisualBasic.Left(sender.Text, 1) = "-" Then
e.Handled = True
End If
ElseIf Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub



Comments

No responses found. Be the first to comment...