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

Categories

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

vb.net - Best way to limit textbox decimal input in c#

How can I make a textbox in which can be only typed a number like 12.00 or 1231231.00 or 123123

I've done this in a very long way and I'm looking for the best and fastest way.

Also the decimal separator must be culture specific.:

Application.CurrentCulture.NumberFormat.NumberDecimalSeparator
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The Validating event was made to do that. Drop an ErrorProvider control on your form so you can subtly remind the user that she did something wrong. The event also allows you to format the text box text the way that make sense. Like this:

    private void textBox1_Validating(object sender, CancelEventArgs e) {
        // Empty strings okay?  Up to you.
        if (textBox1.Text.Length > 0) {
            decimal value;
            if (decimal.TryParse(textBox1.Text, out value)) {
                textBox1.Text = value.ToString("N2");
                errorProvider1.SetError(textBox1, "");
            }
            else {
                e.Cancel = true;
                textBox1.SelectAll();
                errorProvider1.SetError(textBox1, "Please enter a number");
            }
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...