1,105,380 Community Members

Capturing numeric input in a TextBox

Member Avatar
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
 
0
 

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

}
Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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

Member Avatar
arame
Newbie Poster
1 post since Apr 2009
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
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!

Member Avatar
tontano
Newbie Poster
8 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

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

Member Avatar
skatamatic
Posting Shark
980 posts since Nov 2007
Reputation Points: 371 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 5 [?]
 
1
 

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.

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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

Member Avatar
tontano
Newbie Poster
8 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

@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

Member Avatar
skatamatic
Posting Shark
980 posts since Nov 2007
Reputation Points: 371 [?]
Q&As Helped to Solve: 133 [?]
Skill Endorsements: 5 [?]
 
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...)

Member Avatar
ddanbe
Posting Expert
5,355 posts since Oct 2008
Reputation Points: 2,066 [?]
Q&As Helped to Solve: 908 [?]
Skill Endorsements: 46 [?]
Featured
 
0
 

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

You
Post:
Start New Discussion
View similar articles that have also been tagged: