1

I need to add a textbox in my application that starts showing with the value 0.00 just like a ATM, as you type the numbers then it keeps the two decimal point until satisfied with the value for example the sequence to end up of a value of 1023.00 would be (as I type)

0.01
0.10
1.02
10.23
102.30
1023.00

Is this possible to do in a windows forms application?. I am just not sure how to go about it. Thank you.

user710502
  • 11,181
  • 29
  • 106
  • 161
  • 1
    possible duplicate of [Winforms Format TextBox To Currency](http://stackoverflow.com/questions/7258562/winforms-format-textbox-to-currency) – ChrisWue Apr 01 '12 at 07:11

1 Answers1

3

In this kind of scenario I would not use a textbox, but a label or a read-only textbox. To get the user input just use the key-press event on your form (you have to enable KeyPreview on the form too) - then just remember the keys/numbers pressed and output the format you are targeting - should be a rather easy algorithm (Char.IsNumber, and String.Format might come in handy):

    private int _inputNumber = 0;
    private void Form_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (!Char.IsNumber(e.KeyChar)) return;
        _inputNumber = 10*_inputNumber + Int32.Parse(e.KeyChar.ToString());
        ReformatOutput();
    }

    private void ReformatOutput()
    {
         myOutput.Text = String.Format("{0:0.00}", (double)_inputNumber / 100.0);
    }

Note: Why not use a textbox - because it's internal logic with select/replace/remove/type is so overcomplicated that the cases you would have to check are just to much to handle gracefully - so instead of trying to change a cannon into a sling you should start with the sling.

Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • Thank you very much, I can use those functions in a user control that is in the form? – user710502 Apr 01 '12 at 07:45
  • Yes I think that should work too, but the KeyPreview might be an issue if you cannot get a focus on your usercontrol - just try a bit. – Random Dev Apr 01 '12 at 07:58
  • Yeah it works... the only issue i have now is that i have to click somewhere in the form when i arrive at that screen for the numbers to start populating... – user710502 Apr 01 '12 at 08:14
  • you should be able to remove this issue by setting the focus to something in Form_Load – Random Dev Apr 01 '12 at 11:50
  • I see that you are multiplying with 10, how do you implement delete? – Smith Feb 25 '21 at 12:10