我想在每组 3 位数字后添加“,”。例如:当我键入 3000000 时,文本框将显示 3,000,000,但值仍然是 3000000。
我尝试使用 maskedtexbox,有一个缺点是 maskedtexbox 显示了类似 _,__,__ 的数字。
最佳答案
尝试将此代码添加到 TextBox
的 KeyUp
事件处理程序中
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
textBox1.Select(textBox1.Text.Length, 0);
}
}
是的,它会改变存储在文本框中的值,但只要您需要实际数字,您可以使用以下行从文本中获取它:
int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
当然不要忘记检查用户在文本框中输入的内容是否是一个有效的整数。
关于c# - 文本框显示格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7671148/