关于限制输入

来源:互联网 发布:闲徕互娱 知乎 编辑:程序博客网 时间:2024/05/16 10:10

平常经常遇到需要对输入进行限制的时候,经常使用,但是有些东西又记不住,所以干脆写下来。

textBox中只允许输入int数据的情况。
在KeyPress事件中写就可以实现了。

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        
{
            
if ((int)e.KeyChar > 48 & (int)e.KeyChar < 57 || (int)e.KeyChar == 8)
            
{
                e.Handled 
= false;
            }

            
else
            
{
                e.Handled 
= true;
            }

        }

 因为使用到了ASC码,所以要记住对应输入所属的ASC码范围:
0-9对应的ASC码范围是48-57;
大写字母A-Z的ASC码范围是65-90;
小写字母a-z的ASC码范围是97-122;
Back的删除键ASC码是8,Tab键为9,小数点为46

以上也只能限制输入的是整数类型的,要是需要限制的是有小数点的实数,那上面这种方法就不合适了。

<iframe align="middle" marginwidth="0" marginheight="0" src="http://l.thec.cn/lynnlin/googleContent728x90.htm" frameborder="0" width="728" scrolling="no" height="90"></iframe>