如何确定textBox的数据范围

sure356 2010-09-05 05:42:17
我有一个textBox,希望它具备一定的数据检验功能,例如:只能输入0-100间的数,如果为101或者-34,或者abc时能适时提示数据输入格式不正确,请重新输入。即输入10时,没有提示,再加上一个5,即105时,就提示,或者在10前面添加一个-,即-10时,提示错误!
请问各位大神,该如何实现呢?
...全文
91 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
sure356 2010-09-05
  • 打赏
  • 举报
回复
恩,明白了,谢谢您!
兔子-顾问 2010-09-05
  • 打赏
  • 举报
回复
随便粘贴到项目任何一个地方,按F6编译,在工具箱中就会多一个:NumberTextbox
拖出来,用这个控件就可以了。
sure356 2010-09-05
  • 打赏
  • 举报
回复
老感动了!谢谢wuyazhe
可是自己太水了,还不是太理解,这段程序是插入我的form中,还是需要新建一个什么新项呢?
兔子-顾问 2010-09-05
  • 打赏
  • 举报
回复
顺手写了一个给你,你粘贴这个到你项目中。编译。在工具栏中拖出来,用这个就能限制最大最小的一个整数,记得哦,要设置最大Max和最小Min2个值。

public class NumberTextbox : TextBox
{
public int Min { get; set; }
public int Max { get; set; }
public NumberTextbox()
{
Min = 0;
Max = int.MaxValue;
}
protected override void OnKeyPress(KeyPressEventArgs e)
{
e.Handled = !(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)8 || e.KeyChar == '.');
if (!e.Handled) this.Tag = this.Text;//记录最后一次正确输入
base.OnKeyPress(e);
}

protected override void OnTextChanged(EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(this.Text, @"^(?!0\d)\d+(\.\d*)?$"))
{
int index = this.SelectionStart;
this.Text = this.Tag as string;
this.SelectionStart = index;
}
else if (int.Parse(this.Text) > Max || int.Parse(this.Text) < Min)
{
int index = this.SelectionStart;
this.Text = this.Tag as string;
this.SelectionStart = index;
}

base.OnTextChanged(e);
}
}
捷哥1999 2010-09-05
  • 打赏
  • 举报
回复
上面的有一句代码错误了
base.OnKeyPress(e);


应该是
base.OnKeyDown(e);
wuyq11 2010-09-05
  • 打赏
  • 举报
回复
正则验证^(?:100(\.0{1,2})?|[1-9]?[0-9](?:\.[0-9]{1,2})?)$
或验证控件如RangeValidator
sunyu41700 2010-09-05
  • 打赏
  • 举报
回复
textBox添加Validating 事件不就可以吗?
捷哥1999 2010-09-05
  • 打赏
  • 举报
回复


//限制TextBox只能输入数字
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode<Keys.NumPad0 ||e.KeyCode>Keys.NumPad9)
{
if(e.KeyCode<Keys.D0||e.KeyCode>Keys.D9)
{
e.Handled = true;
base.OnKeyPress(e);
}
}
}

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧