Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textbox display formatting

I want to add "," to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedtexbox, there is a drawback that the maskedtexbox displayed a number like _,__,__ .

like image 252
JatSing Avatar asked Oct 31 '25 21:10

JatSing


2 Answers

Try adding this code to KeyUp event handler of your TextBox

private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (!string.IsNullOrEmpty(textBox1.Text))
    {
        System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
        int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
        textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
        textBox1.Select(textBox1.Text.Length, 0);
    }
}

Yes, it will change the value stored in a texbox, but whenever you need the actual number you can use the following line to get it from the text:

int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);

Of course do not forget to check that what the user inputs into the textbox is actually a valid integer number.

like image 118
Dmitrii Erokhin Avatar answered Nov 03 '25 10:11

Dmitrii Erokhin


Use String.Format

int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000

http://msdn.microsoft.com/en-us/library/system.string.format.aspx

like image 44
Cody Avatar answered Nov 03 '25 11:11

Cody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!