Search code examples
c#winformstextbox

Space separator in textBox


Can I have space separator as thousand separator in textbox C#?

  • Example 1:

Write number 58972,56 into textbox and textbox displayed 58 972,56

  • Example 2:

Write number 2358972,56 into textBox and textbox displayed 2 358 972,56


Solution

  • You can clone the Current Culture, change its NumberFormatInfo.NumberGroupSeparator and, eventually, its NumberFormatInfo.CurrencyGroupSeparator and set the values you prefer.
    When you Clone() a CultureInfo object, these properties are not read-only anymore.

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

    The cloned CultureInfo will retain all default values except what you change.
    You can now use the modified CultureInfo where it's needed, without affecting the default Culture behavior.

    In relation to string formatting, see 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);
    

    If you instead want to change the CurrentCulture behavior, assign the modified CultureInfo to the CultureInfo.CurrentCulture object:

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

    Your TextBox could adopt a double-faced logic based on the culture selected.
    When the text is validated, it will be formatted using the modified culture if defined or the default one:

    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;
        }
    }