TextBox in C# separator for thousands when typing

Anaîs laffont 21 Reputation points
2022-09-07T12:45:49.1+00:00

Hello,

Do you know how to do that when you type numbers in a TexBox in c# there is the separator of thousands?

Example : I type 100000 and at the end of the input I get 100 000

Developer technologies C#
0 comments No comments
{count} votes

Accepted answer
  1. Castorix31 90,521 Reputation points
    2022-09-08T00:58:56.663+00:00

    You can add TextChanged event and do something like this (to be improved...) :

            private void textBox1_TextChanged(object sender, EventArgs e)  
            {  
                if (!string.IsNullOrEmpty(textBox1.Text))  
                {  
                    System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();  
                    nfi.NumberGroupSeparator = " ";  
                    double nValue = 0;  
                    bool bError = false;  
                    try  
                    {  
                         nValue = double.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands, nfi);  
                    }  
                    catch (System.Exception se)  
                    {  
                        bError = true;  
                        System.Windows.Forms.MessageBox.Show("Error : " + se.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);  
                    }  
                    finally  
                    {  
                        //if (!bError)  
                        {  
                            textBox1.Text = string.Format(nfi, "{0:N0}", nValue);  
                            textBox1.Select(textBox1.Text.Length, 0);  
                        }                     
                    }  
                }  
            }  
    
    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Anaîs laffont 21 Reputation points
    2022-09-14T21:08:34.317+00:00

    I'm sorry for the delay because I didn't know that you had replied and yet I was watching your reply. Your answer was hidden (you had to click on see more to display your answer)

    I don't really understand your answer... what do you have to do to type the thousand separator with a "." like in your Gif?


  2. Anaîs laffont 21 Reputation points
    2022-09-17T13:46:10.03+00:00

    Hello and thank you,

    Here is the project, I removed the other calculations to make it simple

    I did the test with the button "MontantDuTradeTextBox.Text" but there is a bug when I enter a "."

    https://1drv.ms/u/s!AtJNthPjjq-fhF03iCnuYMvdsDLN


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.