- 24
- 1月
private void textBoxAge_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true; // Remove the charactor
}
}
只要将其加入到TextBox的KeyPress事件订阅之中即可(最好顺便设置一下TextBox的MaxLength属性)
其实现原理是当输入的字符不是数字且不是退格符(ASCII:8)时,告诉控件这个字符已经被处理过了,控件就不会再理会这个字符。