Link to home
Start Free TrialLog in
Avatar of sirbounty
sirbountyFlag for United States of America

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?
ASKER CERTIFIED SOLUTION
Avatar of Brian Mulder
Brian Mulder
Flag of Netherlands image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sirbounty

ASKER

Yeah - I've got 2005 at work, but doing this in 2003. :(

Okay, so this will be currency data, can I allow for a decimal as well?
Incidentally, I found this on another forum...not too bad..
Private Sub NumericKeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) 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
well, then you solved your own question :-)