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

前端 未结 3 2052
隐瞒了意图╮
隐瞒了意图╮ 2020-12-22 00:36

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 01:18

    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.

提交回复
热议问题