Numeric Only TextBox

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 "9") Then
e.Handled = True
End If
End Sub

Example:

TextBox1.MaxLength = 10

 

3 thoughts on “Numeric Only TextBox

  1. 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

  2. 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

Leave a Reply

Your email address will not be published. Required fields are marked *

Bitnami