C# textbox实时输入值检测
C#限制TextBox控件内输入值的范围
1.首先要限制输入的只能是数值
2.再限制输入数值的范围1~100
总结
C# textbox实时输入值检测检查textbox实时输入值是否为英文状态下的,分割符与数值(数值可正可负)
private void textBoxMarker_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '-' || e.KeyChar == ',')
{
e.Handled = false;//允许输入
}
else
{
e.Handled = true;//不允许输入
MessageBox.Show("请输入整型字符(如“-5”“-10”“2”“3”)!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
C#限制TextBox控件内输入值的范围
举个例子:
比如要限制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;
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。