can i format a digit while typing it on a textbx
for example 2343244 will show 2,343,244

any help will be appreciate

6 Years
Discussion Span
Last Post by irandokht

Oops sorry, just re-read your post and realised you were asking if you can format while the text is being entered. The answer to this question is yes, you can handle the TextChanged event in your text box, and then format the number entered. For example:

private void myTextBox_TextChanged(object sender, EventArgs e)
  myTextBox.Text = myTextBox.Text.ToString("0:###,###,##0");

You could use a masked text box instead of a regular text box and just make a mask to match?

I haven't tried, but setting the mask to something like 0,000,000.

I guess the other option would be after the user inputs the data and the textbox loses focus, just run a quick method to get the length of the data input into the box and start inserting "," in the box.

Like this:

private void textBox1_Leave(object sender, EventArgs e)
            //make sure the textbox isn't empty
            if (textBox1.Text != string.Empty)
                //get the data from the textbox
                string TextBoxData = textBox1.Text;

                //use a string builder
                StringBuilder StringBldr = new StringBuilder(TextBoxData);

                //remove any "," strings already in the field in case the user put them in
                StringBldr.Replace(",", "");

                //find out how long the textbox data is
                int TextLength = StringBldr.Length;

                //use 3 here to put a "," every 3 characters
                while (TextLength > 3)
                    StringBldr.Insert(TextLength - 3, ",");
                    TextLength = TextLength - 3;

                textBox1.Text = StringBldr.ToString();


if you wanted it entered as you type you could use the text changed event instead.

I don't like masked textboxes personally, I think they look messy, but they do work just as well...I think....I think masked textboxes can only have a length equal to the mask though...but I could be wrong.


Oops, sorry that line should be:

myTextBox.Text = Convert.ToInt32(myTextBox.Text).ToString("0:###,###,##0");
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.