Monday, June 29, 2009

Validation of numeric field in VB.NET

This code will allow the user to enter digits, '-' symbol(For negative value) and '.'(for decimal) only in the textbox



Private Sub expenseTextboxKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles expenseTextBox.KeyPress, revenueTextBox.KeyPress

'Handles for multiple textboxes

Dim tb As TextBox = CType(sender, TextBox)
Dim chr As Char = e.KeyChar

If IsNumeric(e.KeyChar) And Not e.KeyChar = "-" Then
'If adding the character to the end of the current TextBox value results in
' a numeric value, go on. Otherwise, set e.Handled to True, and don't let
' the character to be added.
e.Handled = Not IsNumeric(tb.Text & e.KeyChar)

ElseIf e.KeyChar = "." Then
'For the decimal character (.) we need a different rule:
'If adding a decimal to the end of the current value of the TextBox results
' in a numeric value, it can be added. If not, this means we already have a
' decimal in the TextBox value, so we only allow the new decimal to sit in
' when it is overwriting the previous decimal.
If Not (tb.SelectedText = "." Or IsNumeric(tb.Text & e.KeyChar)) Then
e.Handled = True
End If

ElseIf e.KeyChar = "-" Then
'A negative sign is prevented if the "-" key is pressed in any location
' other than the begining of the number, or if the number already has a
' negative sign
If tb.SelectionStart <> 0 Or Microsoft.VisualBasic.Left(tb.Text, 1) = "-" Then
e.Handled = True
End If

ElseIf Not Char.IsControl(e.KeyChar) Then
'IsControl is checked, because without that, keys like BackSpace couldn't
' work correctly.
e.Handled = True
End If
End Sub

No comments:

Post a Comment