I would actually use the
Validating
to check the value and use the
KeyPress
(or KeyUp) method to prevent invalid keys being added to the textbox.
This code will prevent anything that isn't "part of a number" being typed into the textbox (Note the inclusion of ,-comma. In some cultures this represents the decimal point)
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
textBox2.CausesValidation = true;
if (new[] { '0','1', '2', '3',
'4', '5', '6', '7', '8', '9', '+',
'-','.', ',','\b' }.Contains(e.KeyChar))
e.Handled = false;
else
e.Handled = true;
}
Then I would have something like this
private void textBox2_Validating(object sender, CancelEventArgs e)
{
const int maxDP = 2;
var txt = ((TextBox)sender).Text.Trim();
if (txt.Length == 0) return;
decimal val;
if (decimal.TryParse(txt, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.CurrentCulture.NumberFormat, out val))
{
if(val != 0 || txt[0] != '-')
if (Math.Round(val * (decimal)(Math.Pow(10, maxDP)), 0)
/ ((decimal)(Math.Pow(10, maxDP))) == val)
return;
}
MessageBox.Show(string.Format("Please enter a decimal value to maximum {0} decimal places", maxDP));
e.Cancel = true;
textBox2.CausesValidation = false;
}
Point of interest is the inclusion of
textBox2.Focus();
textBox2.CausesValidation = false;
when validation fails. This allows the user to close the form if they decide not to bother entering a number.
It has have an associated
private void textBox2_Leave(object sender, EventArgs e)
{
textBox2.CausesValidation = true;
}}
to ensure that validation is switched back on along with the one in KeyPress. There are other (better) ways of achieving this documented by the way.