Hi Team;

I am new to programming and C#. I am creating a calculator form, and need to ensure the user enters a numeric only value (no empty values are valid).

I have 2 text boxes Value 1 & Value 2..The user must enter a numeric value only, and if not a message box should appear.

Here is what I got so far.

private void txValue1_KeyPress(object sender, KeyPressEventArgs e)
            char ch = e.KeyChar;

            if (!Char.IsDigit(ch) && ch != 8 && ch != 13)

                e.Handled = true;


                MessageBox.Show("You have entered an invalid value");


This isn't working for me...I don't know much about the error providor, nor the Validating / Validated events.

Also is it possible to validate both txtboxes at one, or do I need to enter the same code in both textboxes...

Can someone steer me in the right direction..

I hope I entered the code correctly....

Also check out the KeyDown event.

If you want to see a full project that deals with a numeric edit-box, check out this.

It's probably more than you're looking for.

Hi tontano, welcome :)
You could probably use some ideas from this snippet as well.

DDanbe; - The snippet link is not working.
thines01: Thanks

Hopefully I can find a better solution


try this

double outputValue = 0;
                bool number;
                number = double.TryParse(textBox1.Text, out outputValue);
                if (!number)
                    MessageBox.Show("You have entered an invalid value ", "Invalid Input");

Would this be placed in in some sort of validating procedure?
Wow, man, consider the poor user who just has typed a long accesscode with one typo in it. For this he gets punished with a message that tells him little and an empty texbox!
Your users gonna really like your software. This will definitly become a million seller software the world has never seen!!!

I tried this method, bt it doesn't enable to me enter "20"..Only 2 or single numerics works fine...It does what it is supposed to do and that is presents an error when pressing a non-numeric error. Is there something the is preventing me from entering double digits as well as decimals...thanks

    private void txtFValue_KeyDown(object sender, KeyEventArgs e)
            if (!(e.KeyValue >= 48 && e.KeyValue <= 57))
                MessageBox.Show("Please Enter Numbers Only", "Invalid Number");
                txtFValue.Text = "";

    private void txtSValue_KeyDown(object sender, KeyEventArgs e)
            if (!(e.KeyValue >= 48 &&  e.KeyValue <= 57))
                MessageBox.Show("Please Enter Numbers Only", "Invalid Number");
                txtSValue.Text = "";

This doesn't work on my keyboard.
I first have to type the shiftkey(KeyValue=16) to type a digit.
You also don't test for keypad keys!
And why empty the Text after every error, just as barriegrant1 does?
PLease always use code tags.