Thursday, November 26, 2009

Make textbox numeric only with negative value accept

Lets we want to create a textbox which should take only numeric (double/decimal) value and the value can also be in negative
Solution:
Private Sub txt_KeyPressWithNegative(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtothercharges.KeyPress, txtfreight.KeyPress
Dim decexist As Boolean = False

If (CType(sender, TextBox).Text.IndexOf(".") > 0) And e.KeyChar.Equals("."c) Then
decexist = True
End If
If (e.KeyChar = "-") Then
If (CType(sender, TextBox).Text.StartsWith("-") = True) Then
e.Handled = True
Exit Sub
Else
e.Handled = True
CType(sender, TextBox).Text = "-" & CType(sender, TextBox).Text
CType(sender, TextBox).SelectionStart = CType(sender, TextBox).Text.Length
Exit Sub
End If
End If
If (Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) And Not (e.KeyChar.Equals("."c))) Or decexist Then
e.Handled = True
End If
End Sub

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates