Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Textbox in Windows Forms

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?

like image 754
Tigraine Avatar asked Dec 09 '22 22:12

Tigraine


1 Answers

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);
    }
like image 158
Abel Gaxiola Avatar answered Feb 16 '23 10:02

Abel Gaxiola