C# 限制TextBox控件内输入值的范围

时间:2025-03-12 07:41:08

C# 限制TextBox控件内输入值的范围

举个例子,比如要限制TextBox1控件内只能输入1~100的数字(先将TextBox1的MaxLength属性设置成3):
1.首先要限制输入的只能是数值,不能是字母或其他符号;选择添加textBox1的KeyPress事件,代码如下:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(()) &&  != (char)8)
                 = true;
        }

2.再限制输入数值的范围1~100;选择添加textBox1的TextChanged事件,代码如下:

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if ( == "") 
            	 = (); 
            int number = ();
             = ();
            if (number <= 100)
            {
                return;
            }
             = (2);
             = ;
        }