sirbounty
asked on
Prevent non-numeric input
I recall in VB6 that I could basically use the keydown/keypress event to test for the appropriate invalid characters and then just cancel the input (textbox).
What's the proper way for accomplishing this in VB.Net?
What's the proper way for accomplishing this in VB.Net?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Incidentally, I found this on another forum...not too bad..
Private Sub NumericKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPr essEventAr gs) Handles TextBox1.KeyPress
Dim tb As TextBox = sender
If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tb.Text.IndexOf(".") < 0)) Then
e.Handled = True
End If
If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then
e.Handled = True
End If
If e.Handled = False And tb.Text.Length = 0 Then
tb.Text = "$" + e.KeyChar
e.Handled = True
tb.SelectionStart = 2
End If
End Sub
Private Sub NumericKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPr
Dim tb As TextBox = sender
If Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = "." And tb.Text.IndexOf(".") < 0)) Then
e.Handled = True
End If
If (tb.SelectionStart > tb.Text.Length - 2 And tb.Text.IndexOf(".") >= 0 And tb.Text.IndexOf(".") + 3 = tb.Text.Length) Then
e.Handled = True
End If
If e.Handled = False And tb.Text.Length = 0 Then
tb.Text = "$" + e.KeyChar
e.Handled = True
tb.SelectionStart = 2
End If
End Sub
well, then you solved your own question :-)
ASKER
Okay, so this will be currency data, can I allow for a decimal as well?