I want to know how can I add a thousand separator like a comma for my textBox while I am typing a number in it.
i.e. 1,500 instead of 1500.
I want to know how can I add a thousand separator like a comma for my textBox while I am typing a number in it.
i.e. 1,500 instead of 1500.
Fortunately, I solved my problem.
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;
}
we can write this code in the TextChanged method of our textBox to add a thousand separator for the textBox.
by the way, If you wanted to change it later to the first state or if you wanted to use the number in the textbox, in the database, you can use the Replace method.
i.e. textBox1.Text.Replace(",","");
Hope you find it useful.
Method 1 - Add a thousand separator to a TextBox - If you want to add a thousand separator to a TextBox immediately after the client enters a number to the TextBox you can use the code below in the TextChanged event of the TextBox.
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;
}
Method 2 - Add a thousand separator to Label - If you want to add a thousand separators to a label that its text is stable and does not change as a TextBox, you can use the code below that uses NumberFormatInfo helper class.
var separator= new System.Globalization.NumberFormatInfo() {
NumberDecimalDigits = 0,
NumberGroupSeparator = "."
};
var import = 1234567890;
var export = import.ToString("N", separator);
Method 3 - The easiest way to do it - The easiest way to add a thousand separator to a text in a TextBox or a Label is to use the ToString("N") method like the code below,
Convert.ToDouble("1234567.12345").ToString("N")