1

I would like to know how to display two decimal places when we type a value(money) in a text box.

private void txtAmountRecieved_TextChanged(object sender, EventArgs e)
{
    txtAmountRecieved.Text = Convert.ToDouble(txtAmountRecieved.Text)
        .ToString("#,0.00");           
}

I tried above code. But when I type 1 value in textbox, cursor became in-front of value 1. So I cant type continuously in this textbox without interupt. And also an error occurred when I insert this value to database, which is

Input string was not in a correct format.

So how to solve this?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Kith
  • 117
  • 3
  • 17
  • You sure the value of `txtAmountRecieved.Text` can be converted to a `decimal`? – maccettura Jun 19 '18 at 17:43
  • sorry it should be convert.to double – Kith Jun 19 '18 at 17:50
  • Do you want it to format as they type or when they tab to another control? https://stackoverflow.com/questions/19215989/textbox-for-price-cash-currency-on-c-sharp – gunnerone Jun 19 '18 at 17:55
  • You might be better off using a `NumericUpDownControl` – gunnerone Jun 19 '18 at 18:01
  • Possible duplicate of [Textbox for price/cash/currency on C#](https://stackoverflow.com/questions/19215989/textbox-for-price-cash-currency-on-c-sharp) – gunnerone Jun 19 '18 at 18:05
  • What you're doing is going to be difficult in the textchanged event. I mean you could add the line `txtAmountReceived.SelectionStart = txtAmountReceived.Text.IndexOf(".");` but that has its drawbacks too. Anytime you try to manipulate a format on the textchanged you will find yourself fighting the cursor. Plus to elaborate on maccettura's comment, what if the user types something that cannot be converted to a numeric value – Charles May Jun 19 '18 at 19:00
  • thank you gunnerone. Found the exact answer – Kith Jun 19 '18 at 21:36

1 Answers1

3

You can try this. Also you can specify the count after decimal you want

decimal amount= Math.Round(convert.todecimal(textbox.text)), 2);

MaxST
  • 61
  • 1
  • 8