how to format a windows forms Textbox with thousan

2019-01-23 08:00发布

问题:

I'm newbie with Winforms and try to do something. I'm using C#. I'm using windows forms and I've put a 8 textbox on my form, all are numeric with decimal value. I like to achieve the results below. my decimal separator is a comma and thousand separator is a dot. I've ever seen something like ##.###,## or whatever but don't remember.... Can someone advice how to achieve the below approach?

So the idea is when I type 1234 and leave the focus from the textbox it should format and when I get in the textbox back again the thousand separator should not format only the decimal separator.

I think I've to use some events like LostFocus?

input                 result

1234                1.234,00

12.34                    12,34

12,34                    12,34

1234567     1.234.567,00

12,34                    12,34

12345,67     12.345,67

回答1:

On your LostFocus event in textbox, use:

textBox1.Text = string.Format("{0:#,##0.00}", double.Parse(textBox1.Text));

Make sure that the text is double / integer first before applying the above logic or it will throw exception. This solution is rather harsh, tough.

If you want the format to be in specific culture rather than your current computer's culture, then

textBox1.Text = string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:#,##0.00}", double.Parse(textBox1.Text));

The above example is for Indonesian currency format, which thousand separator use dot (".") rather than comma (",").



回答2:

Perhaps you could use the MaskedTextBox

http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.aspx

You could adjust the mask based on the input length when losing focus. Hope this is helpful.