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

any help will be appreciate

Recommended Answers

All 7 Replies

Check out the MaskedTextBox class. This is a text box that all data entry must follow a specific mask (format).

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.

thanks frinds
zachattack05 and darkagn
but when i use this code have an error

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

http://rapidshare.com/files/430687985/error.PNG
what's problem?

Oops, sorry that line should be:

myTextBox.Text = Convert.ToInt32(myTextBox.Text).ToString("0:###,###,##0");

thanks darkagn

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.