I have a Function for checking the input in a textbox and only allowing Numeric & Backspace; everything works fine so far.
My form is for financials and it has about 20 textboxes; they all receive Numeric only data; there is NO alpha data on the entire form required.

Note in the snippet below that I don't even need a decimal point as well.

Is there a way to handle ALL textboxes on this form without having to place the Function call in each textbox KeyPress event.

Relatively new to VB.NET, took a long (5 year) hiatus from developing VB6, appreciate your input.

Public Function TrapKey(ByVal KCode As String) As Boolean
        If (KCode >= 48 And KCode <= 57) Or KCode = 8 Then
            TrapKey = False
            TrapKey = True
        End If
End Function

    'Calling the function on each textbox KeyPress event as:

    e.Handled = TrapKey(Asc(e.KeyChar))
4 Years
Discussion Span
Last Post by themaj

try the below text for all the textboxes keypress event...

   'accepts only numbers
    If (Microsoft.VisualBasic.Asc(e.KeyChar) < 48) Or (Microsoft.VisualBasic.Asc(e.KeyChar) > 57) Then
        e.Handled = True
    End If
    If (Microsoft.VisualBasic.Asc(e.KeyChar) = 8) Then
        e.Handled = False
    End If

This will be too lengthy I guess...coz u will have to code for all 20 text boxes key press....

else create a function similar to it and call the function in key press event


If you set the forms KeyPreview property to True you can use the following code

Public Class Form1

    Private Sub Form1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress

        If Me.ActiveControl.GetType = GetType(TextBox) Then

            Me.Text = e.KeyChar

            Select Case e.KeyChar
                Case "0" To "9"
                Case Chr(Keys.Back)
                Case Else
                    e.Handled = True
            End Select

        End If

    End Sub

End Class

This will restrict all textboxes on the form to 0-9 and backspace. If you need to add non-affected textboxes you can always set the Tag property on the restricted ones and test for that.


Reverend Jim, brilliant !!! Works perfectly.
This will go into my snippet bag for future consideration. VB.NET has so much more to offer but it's a little daunting at times not knowing all the related methods & properties.

I appreciate this, thanks....case closed (but I'll be back for more)....... :)


@Reverend Jim (and all interested)

This works great as a Function, with a tiny bit of modification, if you need it on various forms. Tried using the Tag property to fiilter various textboxes.

Great addition to my snippet library. Thanks again! Give yourself a bonus this week :)

Edited by themaj

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.