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
Can I have space separator as thousand separator in textbox C#?
Write number 58972,56 into textbox and textbox displayed 58 972,56
Write number 2358972,56 into textBox and textbox displayed 2 358 972,56
You can use the Validated
event to format the input:
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");
}
}
It uses the current culture to determine whether to display the decimal separator as decimal point or comma. You can also specify a specific culture:
txt.Text = d.ToString("# ### ### ### ### ##0.00", new CultureInfo("de"));
But in the format string itself always use a decimal point.
The standard way of formatting a TextBox in winforms is to work with data binding. In the binding properties you can specify a format string.
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;
}
}