Sometimes you only want to enter numeric data in a textbox.
You have two options here :
Let a user type whatever he/she wants into a textbox, validate the input and show him or her an annoying message that he/she has done something wrong.:angry:
Or: capture the key before input, check if it's "numeric" and allow only "numerics" to come through. That way, you know the input is correct and you can proceed.:)
A decimal point should be correct input, but only once.
The next snippet does this and is easily adapted to allow for sientific input(+,-,e,E)

bool NumberEntered = false;

//Check if key entered is "numeric".
private bool CheckIfNumericKey(Keys K, bool isDecimalPoint)
    if (K == Keys.Back) //backspace?
        return true;
    else if (K == Keys.OemPeriod || K == Keys.Decimal)  //decimal point?
        return isDecimalPoint ? false : true;       //or: return !isDecimalPoint
    else if ((K >= Keys.D0) && (K <= Keys.D9))      //digit from top of keyboard?
        return true;
    else if ((K >= Keys.NumPad0) && (K <= Keys.NumPad9))    //digit from keypad?
        return true;
        return false;   //no "numeric" key

private void MyTextbox_KeyDown(object sender, KeyEventArgs e)
    //Get our textbox.
    TextBox Tbx = (TextBox)sender;
    // Initialize the flag.
    NumberEntered = CheckIfNumericKey(e.KeyCode, Tbx.Text.Contains("."));

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
private void MyTextbox_KeyPress(object sender, KeyPressEventArgs e)
    // Check for the flag being set in the KeyDown event.
    if (NumberEntered == false)
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;


Line 26 : // This event occurs...
This is of course not the event, this is the event handler method after the event occured.

The best way to do this now is to use the Ajax FilteredTextBoxExtender control.

I thought AJAX to be Asynchronous JavaScript + XML or am I wrong?
Just disscussing a textbox in a plain simple forms application in C# here!

Just so everybody knows what environment I am using. It's C# and Windows Form using Visual Studio 2010.

Wouldn't this allow the user to enter "....." as a number?

I wonder how efficient this would be:

private void MyTextbox_KeyPress(object sender, KeyPressEventArgs e)
    int aDouble = 0;
    // Check for the flag being set in the KeyDown event.
    if (double.TryParse(MyTextBox.Text + e.KeyChar, out aDouble))
        MyTextbox.Tag = aDouble;
        // Stop the character from being entered into the control since it is non-numerical.
        e.Handled = true;

This has the added benefit of storing the numeric value of the textbox in the textbox's .Tag.

Edited 4 Years Ago by skatamatic: n/a

original approach!

@tontano The snippet is real C#, not something else. If you got questions about the code, please feel free to ask.
@skatamatic :
First : "...." question: no, on line 23 I use Tbx.Text.Contains(".")
Second your code:
Line 3 should read double aDouble = 0; I guess.
I could type 1.......
I could correctly type 1.5, but when I use the Tag.ToString() method and showed it in a MessageBox it gave 15
How about backspace?
Still your idea is well worth thinking of :-/

@ddanbe, @skatamatic - Thanks for your effort in helping me..

I do however have a stupid question (at least for me)...What about the use of errorProvider or something like that? Or what about using the events "Validating / Validated"...Again, I know this may sound like a stupid question, and I am sorry for asking....

Thanks guys

Hah sorry for my broken code. I am away from my compiler. I also noticed that the code I posted won't handle negatives unless there's already a number there (since a - by itself is not a valid double, but a -5 is). Not sure about the object.tostring issue, that doesn't really make sense (there is nothing in that code to remove a period...)

@tontano: there are no stupid questions, only stupid answers.
THe whole point of my snippet is just to avoid things like ErrorProvider and Validating!
@skatamatic: You found a flaw in my code! I don't do negatives!Aaargh:@ But then again, I don't do copy and paste either. Maybe I should implement them if I find the time...

Massive bump I know, apolagies.

I've found your code very useful thanks ddanbe, buuut I was wondering if there is a way to allow a decimal point to be input before anything else in the textbox? Currently it crashes the solution :S I've tried editing the current code but to no avail (I'm very new to this).

Any help would be much appreciated!