Search code examples
c#winformstextbox

How to add a thousand separator for a textbox in Winforms, C#


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.


Solution

  • 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.