怎样控制TextBox控件只输入数字?

aluony 2002-11-22 11:35:14
我记得在delphi中可以在keyPress事件中修改key值达到目的。
而在C#中e.KeyChar是只读的参数,怎么办呢?
...全文
699 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
superkiller 2002-11-22
  • 打赏
  • 举报
回复
webform
加入RegularExpressionValidator 控件
ValidationExpression \d*
暗石绿 2002-11-22
  • 打赏
  • 举报
回复
这只是在WindowForm里面能有,请问有没有在WebForm里面控制TextBox输入数字的方法?
TheAres 2002-11-22
  • 打赏
  • 举报
回复
1.---------------------
作textbox的KeyPress中:
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && (e.KeyChar != 8))
e.Handled = true;
base.OnKeyPress(e);

}

说明:
e.KeyChar != 8是为了让退格键起作用

2.-----------------------------
If somebody use copy/paste, It also can paste something into the textbox, so and the following code to textchange event.

private void textBox1_TextChanged(object sender, System.EventArgs e)
{
if(!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text,@"^\d*$"))textBox1.Undo();
}

110,525

社区成员

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

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

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