举个例子,比如要限制TextBox1控件内只能输入1~100的数字(先将TextBox1的MaxLength属性设置成3):
1.首先要限制输入的只能是数值,不能是字母或其他符号;选择添加textBox1的KeyPress事件,代码如下:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)8)
e.Handled = true;
}
2.再限制输入数值的范围1~100;选择添加textBox1的TextChanged事件,代码如下:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text == "")
textBox1.Text = 0.ToString();
int number = int.Parse(textBox1.Text);
textBox1.Text = number.ToString();
if (number <= 100)
{
return;
}
textBox1.Text = textBox1.Text.Remove(2);
textBox1.SelectionStart = textBox1.Text.Length;
}