如何在 Winforms, C# 中为文本框添加千位分隔符
How to add a thousand separator for a textbox in Winforms, C#
我想知道如何在我的文本框中添加千位分隔符(如逗号),同时在其中输入数字。
即1,500 而不是 1500。
幸运的是,我解决了我的问题。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "0") return;
decimal price;
price = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
textBox1.Text = price.ToString("#,#");
textBox1.SelectionStart = textBox1.Text.Length;
}
我们可以在 textBox 的 TextChanged 方法中编写这段代码,为文本框添加千位分隔符。
顺便说一句,如果你想稍后将其更改为第一个状态,或者如果你想使用文本框中的数字,在数据库中,你可以使用 Replace 方法。
即textBox1.Text.Replace(",","");
希望您觉得它有用。
方法 1 - 向文本框添加千位分隔符 -
如果您想在客户端向 TextBox 输入数字后立即向 TextBox 添加千位分隔符,您可以在 TextBox 的 TextChanged 事件中使用下面的代码。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "0") return;
decimal number;
number = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
textBox1.Text = number.ToString("#,#");
textBox1.SelectionStart = textBox1.Text.Length;
}
方法二-给Label添加千位分隔符-
如果要向其文本稳定且不会更改为文本框的标签添加千位分隔符,则可以使用下面使用 NumberFormatInfo 帮助器 class.
的代码
var separator= new System.Globalization.NumberFormatInfo() {
NumberDecimalDigits = 0,
NumberGroupSeparator = "."
};
var import = 1234567890;
var export = import.ToString("N", separator);
方法 3 - 最简单的方法 -
向 TextBox 或 Label 中的文本添加千位分隔符的最简单方法是使用 ToString("N") 方法,如下面的代码,
Convert.ToDouble("1234567.12345").ToString("N")
我想知道如何在我的文本框中添加千位分隔符(如逗号),同时在其中输入数字。
即1,500 而不是 1500。
幸运的是,我解决了我的问题。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "0") return;
decimal price;
price = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
textBox1.Text = price.ToString("#,#");
textBox1.SelectionStart = textBox1.Text.Length;
}
我们可以在 textBox 的 TextChanged 方法中编写这段代码,为文本框添加千位分隔符。
顺便说一句,如果你想稍后将其更改为第一个状态,或者如果你想使用文本框中的数字,在数据库中,你可以使用 Replace 方法。
即textBox1.Text.Replace(",","");
希望您觉得它有用。
方法 1 - 向文本框添加千位分隔符 - 如果您想在客户端向 TextBox 输入数字后立即向 TextBox 添加千位分隔符,您可以在 TextBox 的 TextChanged 事件中使用下面的代码。
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox1.Text == "0") return;
decimal number;
number = decimal.Parse(textBox1.Text, System.Globalization.NumberStyles.Currency);
textBox1.Text = number.ToString("#,#");
textBox1.SelectionStart = textBox1.Text.Length;
}
方法二-给Label添加千位分隔符- 如果要向其文本稳定且不会更改为文本框的标签添加千位分隔符,则可以使用下面使用 NumberFormatInfo 帮助器 class.
的代码var separator= new System.Globalization.NumberFormatInfo() {
NumberDecimalDigits = 0,
NumberGroupSeparator = "."
};
var import = 1234567890;
var export = import.ToString("N", separator);
方法 3 - 最简单的方法 - 向 TextBox 或 Label 中的文本添加千位分隔符的最简单方法是使用 ToString("N") 方法,如下面的代码,
Convert.ToDouble("1234567.12345").ToString("N")