tags:

views:

983

answers:

3

How to suppress all data except numeric, this is not working on KeyDown()

   If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
            e.Handled = True
   End If
+2  A: 

You can check Char.IsDigit(e.KeyChar) but the best thing to do in this case is to create a subclass of TextBox and override IsInputChar(). That way you have a reusable TextBox control that you can drop anywhere and not have to re-implement the logic.

(My VB is a bit rusty...)

Public Class NumericTextBox Inherits TextBox

    Protected Overrides Function IsInputChar(Byval charCode As Char) As Boolean
        If (Char.IsControl(charCode) Or Char.IsDigit(charCode)) Then
            Return MyBase.IsInputChar(charCode)
        Else
            Return False
        End If
    End Function

End Class
Josh Einstein
Don't forget to allow (localized) thousand and decimal separators
Fredrik Mörk
Will this handle cases where the text is pasted in from the clipboard?
Chris Dunaway
A: 

I suggest that you use regular expressions. you can search google like 'regular expression textbox only numeric' and i guess you'll come up with many examples.

For example if you are in asp.net you can do it like:

<asp:TextBox ID="txtPhoneNumber" runat="server" Text='<%#Bind("phoneNumber") %>' MaxLength="15"></asp:TextBox>
<asp:RegularExpressionValidator ID="rfvUSerPhoneNumberValidate" runat="server"
ControlToValidate="txtPhoneNumber" Display="Dynamic" ValidationExpression="^[0-9]{1,15}$"  
ErrorMessage="Please enter only numeric value for Phone Number" EnableViewState="true">
</asp:RegularExpressionValidator>
davsan
A: 

There are many ways to do this. I've had a quick stab at it and go this which works. I have used the KeyPress sub for the textbox, and pass each keypress to the IsNumber function.

NOTE: I have allowed the backspace key to be used in case you make a mistake with the numbers and want to deleted.

Take out the If e.KeyChar <> ChrW(Keys.Back) Then / End If part if you dont need the backspace.

    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    If e.KeyChar <> ChrW(Keys.Back) Then
        If Char.IsNumber(e.KeyChar) Then
        Else
            e.Handled = True
        End If
    End If
End Sub
kevchadders
What about the delete key? What about cut and paste from the clipboard?
Chris Dunaway
Certainly, they could be added into the IF statement to ignore. Good Point.
kevchadders