Space 文本框中的分隔符

Space separator in textBox

我可以在文本框 C# 中使用 space 分隔符作为千位分隔符吗?

将数字58972,56写入文本框,文本框显示58 972,56

将数字2358972,56写入文本框,文本框显示2 358 972,56

您可以使用 Validated 事件来格式化输入:

private void TextBox1_Validated(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    if (Decimal.TryParse(txt.Text, out var d)) {
        txt.Text = d.ToString("# ### ### ### ### ##0.00");
    }
}

它使用当前的文化来确定小数分隔符是显示为小数点还是逗号。您还可以指定特定的文化:

txt.Text = d.ToString("# ### ### ### ### ##0.00", new CultureInfo("de"));

但格式字符串本身总是使用小数点。


在 winforms 中格式化文本框的标准方法是使用 data binding。在绑定属性中,您可以指定格式字符串。

您可以克隆当前文化,更改其 NumberFormatInfo.NumberGroupSeparator and, eventually, its NumberFormatInfo.CurrencyGroupSeparator 并设置您喜欢的值。
当您 Clone() a CultureInfo 对象时,这些属性不再是只读的。

The clone is writable even if the original CultureInfo is read-only. Therefore, the properties of the clone can be modified.

克隆的 CultureInfo 将保留所有默认值,但您更改的内容除外。
您现在可以在需要的地方使用修改后的 CultureInfo,而不会影响默认的 Culture 行为。

关于字符串格式,请参阅 Standard numeric format strings

var culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
culture.NumberFormat.NumberGroupSeparator = " ";
culture.NumberFormat.CurrencyGroupSeparator = " ";

// Elsewhere
[TextBox1].Text = 12345678.89.ToString("N2", culture);

[TextBox2].Text = 12345678.89M.ToString("C", culture);

如果您想更改 CurrentCulture 行为,请将修改后的 CultureInfo 分配给 CultureInfo.CurrentCulture 对象:

CultureInfo.CurrentCulture = culture;

// elsewhere: same behavior, now the default
[TextBox1].Text = 12345678.89.ToString("N2");

您的 TextBox 可以根据所选区域性采用双面逻辑。
验证文本后,将使用修改后的文化(如果已定义)或默认文化对其进行格式化:

private void textBox_Validating(object sender, CancelEventArgs e)
{
    var numberStyle = NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint;
    if (double.TryParse(textBox.Text, numberStyle, culture ?? CultureInfo.CurrentCulture, out double value)) {
        textBox.ForeColor = SystemColors.ControlText;
        textBox.Text = value.ToString("N", culture ?? CultureInfo.CurrentCulture);
    }
    else {
        // Notify, change text color, whatever fits
        textBox.ForeColor = Color.Red;
    }
}