Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - 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 _,__,__ .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...