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
856 views
in Technique[技术] by (71.8m points)

c# - Only allowing up to three digit numeric characters in a text box

Is there a way to only allow a user to input a maximum number of characters into a text box? I want the user to input a mark/grade and only be able to input 0 - 100. Below I have code that monitors the keystroke and only allows for numbers to be input, but I want to find a way to only allow the user to input a number with a minimum value of 0 and a maximum of 100.

private void TxtMark4_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar < '0' || e.KeyChar > '9' || e.KeyChar == ' ')
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

or I could use the following:

if (e.KeyChar >= 48 && e.KeyChar <= 57 || e.KeyChar == ' ')
{
    e.Handled = false;
}
else
{
    MessageBox.Show("You Can Only Enter A Number!");
    e.Handled = true;
}

But I would like to find a way to only allow three characters to be input maximum.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I think it is as simple as:

textBox1.MaxLength = 3;

Then you handle the maximum value on the Leave event:

    private void textBox1_Leave(object sender, EventArgs e)
    {
        string s = (sender as TextBox).Text;
        int i = Convert.ToInt16(s);

        if (i > 100)
        {
            MessageBox.Show("Number greater than 100");
            (sender as TextBox).Focus();
        }
    }

or

You could also use System.Windows.Forms.NumericUpDown where you can easily setup minimum and maximum.


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

1.4m articles

1.4m replys

5 comments

57.0k users

...