views:

2027

answers:

4

Hi,

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?

+4  A: 

You will need a custom control. Just trap the Validating event on the control and check if the string input can be parsed as a decimal.

Nick
Thanks.. that leaves me with the next challenge.. create a custom control *gg* ..
Tigraine
A: 

MSDN: User Input Validation in Windows Forms

Mr. Brownstone
+2  A: 

I don't think you need a custom control, just write a decimal validating method for the validating event and use that for all the places you need to validate. Don't forget to include the NumberFormatInfo, it will deal with commas and numebr signs.

nportelli
Having a custom control ready to go would save him a bunch of boilerplate code everywhere he needs to hook this up: it's a good thing to do.
Joel Coehoorn
+3  A: 

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);
    }
Abel
Thanks a lot. I implemented this with a custom control and also blogged about it:http://www.tigraine.at/2008/10/28/decimaltextbox-for-windows-forms/
Tigraine