How to format a Windows Forms Textbox with thousand separator and decimal separtor for numeric input(如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入)
问题描述
我是 Windows 窗体的新手并尝试做一些事情.我正在使用 C#.
I'm new to Windows Forms and try to do something. I'm using C#.
我使用的是 Windows 窗体,我在窗体上放置了八个文本框,并且都是带有十进制值的数字.
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?
所以我的想法是,当我输入 1234 并将焦点从文本框中移开时,它应该格式化,当我再次回到文本框时,千位分隔符不应该只格式化小数分隔符.
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.
我想我必须使用一些事件,比如 LostFocus.
I think I've to use some events like LostFocus.
输入 结果
1234 1.234,00
1234 1.234,00
12.34 12,34
12.34 12,34
12,34 12,34
12,34 12,34
1234567 1.234.567,00
1234567 1.234.567,00
12,34 12,34
12,34 12,34
12345,67 12.345,67
12345,67 12.345,67
推荐答案
在文本框中的 LostFocus 事件中,使用:
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 (",").
这篇关于如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用千位分隔符和小数分隔符格式化 Windows 窗体文本框以进行数字输入
基础教程推荐
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
