Decimal Text Box in Windows Forms

I am making a Financial Winforms application and am having problems with controls.

My client should insert decimal values ​​all over the place (prices, discounts, etc.) and I would like to avoid re-checking.

So, I immediately tried MaskedTextBox, which would suit my needs (with a mask like "€ 00000.00"), if not for the focus and length of the mask.

I can not predict how large the numbers that my client is going to enter the application.

I also cannot expect it to start at 00 to get to the decimal point. Everything should be comfortable for the keyboard.

Am I missing something or not just (outside of writing a custom control) to achieve this using standard Windows Forms controls?

+3
source share
5 answers

These two redefinition methods did it for me (disclaimer: this code is not ready to work yet. You may need to change it)

    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);
    }
+5
source

You will need a custom control. Just lock the Validating event on the control and see if syntax input can be treated as decimal.

+5
source

, , , . NumberFormatInfo, numebr.

+3
+1

You only need to skip numbers and decimals and avoid double decimal places. In addition, it automatically adds 0 to the starting decimal.

public class DecimalBox : TextBox
{
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if (e.KeyChar == ',')
        {
            e.KeyChar = '.';
        }

        if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        if(e.KeyChar == '.' )
        {
            if (this.Text.Length == 0)
            {
                this.Text = "0.";
                this.SelectionStart = 2;
                e.Handled = true;
            }
            else if (this.Text.Contains("."))
            {
                e.Handled = true;
            }
        }

        base.OnKeyPress(e);
    }
}
0
source

Source: https://habr.com/ru/post/1698802/


All Articles