Tigraine

Daniel Hoelbling-Inzko talks about programming

DecimalTextbox for Windows Forms

I’ve been doing some Windows Forms development lately and really love it. After doing web development for the last couple of years I am thankful for the change. Being able to create compelling UIs without having to worry about Javascript is something I’ve been longing for quite some time.

But when trying to build intuitive and user-friendly UIs, you hit the boundaries of Microsoft’s control toolbox pretty fast. (Not as fast as with Webcontrols, but still).
I needed a Textbox that accepts only decimal input and that formats itself rather nicely for a finance application I’m building right now.

I first turned to the MaskedTextBox control that’s already there, but that turned out to be completely useless because numbers have no fixed length.
So I decided to create a Custom Control that derives from TextBox that does exactly what I need – take decimals and nothing else.

The whole process is rather simple, so I’ll just give you the code and be done with it. The DecimalTextbox control won’t accept any input that’s not numeric except for one comma. If you leave the control empty or non-decimal (however you accomplish that) it will revert to 0,00 on validation.

The code is after the break

public partial class DecimalTextBox : TextBox
{
    public DecimalTextBox()
    {
        InitializeComponent();
    }

    protected override void OnTextChanged(EventArgs e)     {         if (IsDecimal())             base.OnTextChanged(e);     }

    protected override void OnKeyPress(KeyPressEventArgs e)     {         if (!char.IsNumber(e.KeyChar)             && ((Keys)e.KeyChar != Keys.Back)             && (e.KeyChar != ','))             e.Handled = true;

        if (e.KeyChar == ',' && Text.IndexOf(',') > 0)             e.Handled = true;

        base.OnKeyPress(e);     }

    protected override void OnGotFocus(EventArgs e)     {         ResetValueOnFocus();         base.OnGotFocus(e);     }

    private void ResetValueOnFocus()     {         if (IsDecimal())         {             if (!IsDecimalZero())                 return;         }         Text = "";     }

    private bool IsDecimal()     {         decimal result;         return decimal.TryParse(Text, out result);     }

    private bool IsDecimalZero()     {         return (decimal.Parse(Text) == 0);     }

    private void DecimalTextBox_Validating(object sender, CancelEventArgs e)     {         decimal value;         decimal.TryParse(Text, out value);

        const string NUMBER_FORMAT_2_DIGITS = "N2";         Text = value.ToString(NUMBER_FORMAT_2_DIGITS);     }

    public decimal Value     {         get         {             return decimal.Parse(Text);         }     } }

And since copying source from HTML sucks here’s the DecimalTextBox.cs.

My Photography business

Projects

dynamic css for .NET

Archives

more