2

How do I 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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tom
  • 6,725
  • 24
  • 95
  • 159
  • 1
    I think you can find your answer here: http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers (don't miss to pay attention to the comment by Jeff Yates) – Fredrik Mörk Jun 02 '09 at 07:39

9 Answers9

6

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
  • 8,335
  • 4
  • 42
  • 61
4

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 so you don't 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
Anonymous Pi
  • 125
  • 7
Josh
  • 68,005
  • 14
  • 144
  • 156
1

This code will help you to restrict multiple TEXTBOX to accept only NUMERIC VALUE and BACKSPACE key. However you can remove If e.KeyChar <> ChrW(Keys.Back) Then and End If value from code when you don't want to accept backspace key. Enhanced version of the kevchadders solution in this thread.

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress
    If e.KeyChar <> ChrW(Keys.Back) Then
        If Char.IsNumber(e.KeyChar) Then
        Else
            e.Handled = True
        End If
    End If
End Sub
1

Will help you...

    Public Function IsNumericTextbox(ByVal sender As TextBox, ByVal KeyChar As Char) As Boolean
    'set TRUE: cause a exception when the keychar is not Allowed into vars: allowedChars, allowedOneChar, allowedExceptionChar
    Dim UseThrowDebuggy As Boolean = False

    Dim allowedChars As String = "0123456789"
    Dim allowedOnceChar As Char() = {"."}
    Dim allowedExceptionChar As Keys() = {Keys.Back}

    Dim idxAllowedNotFound As Integer
    Dim idxCountOne As Integer = 0

    idxAllowedNotFound = allowedChars.IndexOf(KeyChar)
    If idxAllowedNotFound = True Then
        'AllowedOnce
        For Each _c As Char In allowedOnceChar
            If _c = KeyChar Then
                'Count Check
                For Each _cc As Char In sender.Text
                    If _c = _cc Then idxCountOne += 1
                Next
                If idxCountOne = 0 Then
                    Return False
                Else
                    Return True
                End If
            End If
        Next
        'Exceptions
        For i As Integer = 0 To allowedExceptionChar.Count - 1
            If Asc(KeyChar) = Convert.ToUInt32(allowedExceptionChar(i)) Then Return False
        Next
        'Not Throw
        If UseThrowDebuggy = False Then
            If Char.IsNumber(KeyChar) Then
                Return False
            Else
                Return True
            End If
        End If
        'Outside to end for throw
    Else
        'AllowedChars
        Return False
    End If

    Dim _kc As String = ControlChars.NewLine & "Char: " & KeyChar & ControlChars.NewLine & "Asc: " & Asc(KeyChar) & ControlChars.NewLine
    Throw New Exception("UseThrowDebuggy found a unknow KeyChar: " & _kc)
End Function

For use my function add this code into a textbox_keypress:

e.Handled = IsNumericTextbox(sender, e.KeyChar)

1
 Public Class NumericTextBox : Inherits System.Windows.Forms.TextBox

 Protected Overrides Sub OnKeyPress(e As Windows.Forms.KeyPressEventArgs)
      If Char.IsDigit(e.KeyChar) Or
          Char.IsControl(e.KeyChar) Or
          e.KeyChar = lobalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator Then
      MyBase.OnKeyPress(e)
    Else
        e.Handled = True
    End If
 End Sub

 End Class
0

This will allow numeric input ,Backspace to correct your input , and also a decimal point.

    If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> ControlChars.Cr AndAlso e.KeyChar <> "." Then
        Beep()
        e.Handled = True
    End If
0

This is another way to restrict number inputs into textbox . using KEYPRESS Events

If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then MessageBox.Show("Only Numbers") e.Handled = True End If End Sub hope it helps ! thnks ..

0

The purpose of your function could help provide additional solutions. Checking for a numeric value on each KeyPress is likely overkill. Then you have to overkill it more by accounting for backspace, delete, copy, paste, etc.

For example, if you are storing a telephone number, you should use the "IsNumeric" function on the validate and update step. Alternatively, if you are selecting quantity of an item "NumericUpDown" control would be more appropriate than a TextBox.

Jon Milliken
  • 121
  • 11
0

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
aslı
  • 8,740
  • 10
  • 59
  • 80