Question Textbox numbers only

tqmd1

Well-known member
Joined
Dec 5, 2009
Messages
60
Programming Experience
Beginner
On Form Level, I use following codes to make textboxes to accept only numbers,

How to add these codes in main module, instead of of writing these codes on every form.

Please modify

VB.NET:
 If TypeName(Me.ActiveControl) = "TextBox" Then
            With Me.ActiveControl
                If Not IsNumeric(.Text) And .Text <> vbNullString Then
                    MsgBox("Sorry, only numbers allowed")
                    .Text = vbNullString
                    .Text = Nothing
                End If
            End With
        End If
Please help
 
Last edited:
Try something like
VB.NET:
'in a module
Module Module1

    Public dblNumber As Double = 0

    Public Sub AllowOnlyNumbers(ByVal pstrTB As TextBox)
        If pstrTB.Text.Trim() <> String.Empty Then
            If Not Double.TryParse(pstrTB.Text, dblNumber) Then
                pstrTB.Text = String.Empty
                MessageBox.Show("The text in this box must be strickly numbers!", _
                "Numbers Only", _
                MessageBoxButtons.OK, _
                MessageBoxIcon.Warning)
                pstrTB.Focus()
                Exit Sub
            End If
        End If
    End Sub
End Module

'on a form
Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox2.KeyPress
        AllowOnlyNumbers(TextBox2)
End Sub
 
Dear Sir,

When I call sub AllowOnlyNumbers() form module and write AllowOnlyNumbers on keypress event of any textbox then it says

HTML:
Argument not specified for parameter 'pstrTB' of 'Public Sub AllowOnlyNumbers(pstrTB As System.Windows.Forms.TextBox)'.

Please help again
 
That is correct and to be expected.

You don't call it but simply typing in - AllowOnlyNumbers

Look at my example.

You have to pass it the name of the textbox.
 
Back
Top