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)
Capturing numeric input in a TextBox
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
arame 0 Newbie Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
tontano 0 Newbie Poster
ddanbe 2,724 Professional Procrastinator Featured Poster
tontano 0 Newbie Poster
skatamatic 371 Practically a Posting Shark
ddanbe 2,724 Professional Procrastinator Featured Poster
Morgan_2 0 Newbie Poster
noface0711 0 Newbie Poster
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.