Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - How to format a Windows Forms Textbox with thousand separator and decimal separtor for numeric input

I'm new to Windows Forms and try to do something. I'm using C#.

I'm using Windows Forms and I've put eight textboxes on my form, and 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.... How can i 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On your LostFocus event in the 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 an exception. This solution is rather harsh, tough.

If you want the format to be in a 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 the Indonesian currency format, in which the thousand separator use dot (".") rather than comma (",").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...