Numeric Only TextBox

Griffin picture Griffin · Dec 24, 2011 · Viewed 9.6k times · Source

I've looked all over the place, but it seems that examples I have seen allow only numbers 0-9

I'm writing a Pythagorean Theorem program. I wish to have the phone (Windows Phone 7) check if there are ANY alpha (A-Z, a-z), symbols (@,%), or anything other than a number in the textbox. If not, then it will continue computing. I want to check so there will be no future errors.

This is basically a bad pseudocode of what I want it to do

txtOne-->any alpha?--No-->any symbols--No-->continue...

I would actually prefer a command to check if the string is completely a number.

Thanks in advance!

Answer

Marlon picture Marlon · Dec 24, 2011

An even better way to ensure that your textbox is a number is to handle the KeyPress event. You can then choose what characters you want to allow. In the following example we disallow all characters that are not digits:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // If the character is not a digit, don't let it show up in the textbox.
    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;
}

This ensures that your textbox text is a number because it only allows digits to be entered.


This is something I just came up with to allow decimal values (and apparently the backspace key):

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsDigit(e.KeyChar))
    {
        return;
    }
    if (e.KeyChar == (char)Keys.Back)
    {
        return;
    }
    if (e.KeyChar == '.' && !textBox1.Text.Contains('.'))
    {
        return;
    }
    e.Handled = true;
}