I am doing an Financial Winforms application and am having some trouble with the controls.
My customer needs to insert decimal values all over the place (Prices, Discounts etc) and I'd like to avoid some of the repeating validation.
So I immediately tried the MaskedTextBox that would fit my needs (with a Mask like "€ 00000.00"), if it weren't for the focus and the length of the mask.
I can't predict how big the numbers are my customer is going to enter into the app.
I also can't expect him to start everything with 00 to get to the comma. Everything should be keyboard-friendly.
Am I missing something or is there simply no way (beyond writing a custom control) to achieve this with the standard Windows Forms controls?
This two overriden methods did it for me (disclaimer: this code is not in production yet. You may need to modify)
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back
& e.KeyChar != '.')
{
e.Handled = true;
}
base.OnKeyPress(e);
}
private string currentText;
protected override void OnTextChanged(EventArgs e)
{
if (this.Text.Length > 0)
{
float result;
bool isNumeric = float.TryParse(this.Text, out result);
if (isNumeric)
{
currentText = this.Text;
}
else
{
this.Text = currentText;
this.Select(this.Text.Length, 0);
}
}
base.OnTextChanged(e);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With