怎样实现一个TextBox,只接受数字输入,并且限制最大和最小值?

fifa 2003-07-02 03:11:22
怎样实现一个TextBox,只接受数字输入,并且限制最大和最小值?
我按下面方式做时,发生死循环。高分求购解决方法。

class DigitalBox : TextBox;

// 排斥非数字输入
protected override void OnKeyPress(KeyPressEventArgs e)
{
if ( e.KeyChar >= '0' && e.KeyChar <= '9' )
{
string str = (string)this.Text.Clone();
base.OnKeyPress( e );
int v = int.Parse(this.Text);
if ( v < minValue || v > maxValue )
{
this.Text = str;
e.Handled = true;
}
}
else
{
e.Handled = true;
}
}
...全文
837 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
好运 2003-07-23
  • 打赏
  • 举报
回复
好像都没有提到小数点的问题
working1997 2003-07-02
  • 打赏
  • 举报
回复
http://expert.csdn.net/Expert/topic/1961/1961842.xml?temp=.3377039
fifa 2003-07-02
  • 打赏
  • 举报
回复
// 问题已解决,只有调用base.OnKeyPress后,this.Text的值才会改变,但在OnKeyPress
// 处理中又不能给this.Text赋值,否则会造成死循环,还应该考虑选择替换的情况。
// 我的代码如下:
protected override void OnKeyPress(KeyPressEventArgs e)
{
if ( e.KeyChar >= '0' && e.KeyChar <= '9' )
{
string str = this.Text;
if ( this.SelectedText != "" )
{
str = str.Remove(this.SelectionStart, this.SelectionLength);
}

str = str.Insert(this.SelectionStart, e.KeyChar.ToString());
int v = 0;
if ( str != "") v = int.Parse(str);
if ( v < minValue || v > maxValue )
{
e.Handled = true;
}
else
{
base.OnKeyPress( e );
}
}
else if ( e.KeyChar == (char)8 ) // backspace Key
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
mwpg79 2003-07-02
  • 打赏
  • 举报
回复
base.OnKeyPress(e);
int v=Int32.Parse(this.Text+e.KeyChar.Tostring());
if( v>MaxValue || v<MinValue || e.KeyChar<'0' || e.KeyChar>'9')
{
e.Handled=true;
return;
}
else e.Handled=false;
brightheroes 2003-07-02
  • 打赏
  • 举报
回复
同意ismezy2002(扬)
kinglht 2003-07-02
  • 打赏
  • 举报
回复
使用 RangeValidator
参考
http://chs.gotdotnet.com/quickstart/aspplus/doc/webvalidation.aspx#range
zuohaijun 2003-07-02
  • 打赏
  • 举报
回复
用验证控件RangeValidator
设置max...min...的值。
设置controltovavidate是验证哪个控件
type控制类型....
chNET 2003-07-02
  • 打赏
  • 举报
回复

http://expert.csdn.net/Expert/topic/1843/1843288.xml?temp=.4445459
ismezy2002 2003-07-02
  • 打赏
  • 举报
回复
protected override void OnKeyPress(KeyPressEventArgs e)
{
if ( e.KeyChar < '0' && e.KeyChar > '9' )
{
e.Handled = true;
}
else
{
int v = int.Parse(this.Text);
if ( v < minValue || v > maxValue ) e.Handled = true;
}
}
ismezy2002 2003-07-02
  • 打赏
  • 举报
回复
protected override void OnKeyPress(KeyPressEventArgs e)
{
if ( e.KeyChar < '0' && e.KeyChar > '9' )
{
e.Handled = true;
}
}
rqxiang 2003-07-02
  • 打赏
  • 举报
回复
验证控件

110,538

社区成员

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

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

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