Capturing numeric input in a TextBox

ddanbe 1 Tallied Votes 3K Views Share

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;
    else
        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;
    }

}
ddanbe 2,724 Professional Procrastinator Featured Poster

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

arame 0 Newbie Poster

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

ddanbe 2,724 Professional Procrastinator Featured Poster

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!

tontano 0 Newbie Poster

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

skatamatic 371 Practically a Posting Shark

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;
    else
        // 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.

ddanbe commented: original approach! +15
ddanbe 2,724 Professional Procrastinator Featured Poster

@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 :-/

tontano 0 Newbie Poster

@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

skatamatic 371 Practically a Posting Shark

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

ddanbe 2,724 Professional Procrastinator Featured Poster

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

Morgan_2 0 Newbie Poster

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!

noface0711 0 Newbie Poster

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.