Numeric Only TextBox

2:31 AM
It's Very Easy to make a Numeric only TextBox ..
Just right the Following Code on The Textbox's KeyPress Event..

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
            {
                e.Handled = true;
            }
        }


Above Code Wont Let you enter anything other than 0 to 9 Numerics

To Limit the Number of Character in Texbox use the MaxLength Property  of Texbox

Example:

TextBox1.MaxLength = 10;


Vb.net

 Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If e.KeyChar > "31" And (e.KeyChar < "0" Or e.KeyChar > "9") Then
            e.Handled = True
        End If
    End Sub


Example:

TextBox1.MaxLength = 10


3 comments:

{ Unknown } at: July 31, 2012 at 12:07 PM said...

This still allows for special characters such as: ',./ and the like.

The following is what i have used which allows the user to backspace and prevents any special characters:

If Not IsNumeric(e.KeyChar) AndAlso e.KeyChar <> ControlChars.Back Then e.Handled = True

{ Unknown } at: February 7, 2013 at 6:04 AM said...

Thanks :)

{ vicsar } at: May 3, 2016 at 3:55 PM said...

Here is an example for a text box on a BMI calculator I am working on.

Private Sub txtWeight_TextChanged(sender As Object, e As EventArgs) Handles txtWeight.TextChanged
If txtWeight.Text = "" Then
GoTo ex
Else
If IsNumeric(txtWeight.Text) Then
GoTo ex
Else
MsgBox("You cannot add alpha characters, please input the Integer or numbers !", vbCritical)
txtWeight.Text = ""

End If
End If
ex:
Exit Sub
End Sub

Post a Comment