954,505 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?

Capturing numeric input in a TextBox

0
By Marivoet Daniel on Feb 7th, 2009 11:38 pm

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

}

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

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

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

arame
Newbie Poster
1 post since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

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!

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

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

tontano
Newbie Poster
8 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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.

skatamatic
Posting Shark
959 posts since Nov 2007
Reputation Points: 403
Solved Threads: 129
 

@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
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

@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

tontano
Newbie Poster
8 posts since Feb 2012
Reputation Points: 10
Solved Threads: 0
 

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

skatamatic
Posting Shark
959 posts since Nov 2007
Reputation Points: 403
Solved Threads: 129
 

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

ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: