C#控制textbox只能填写数字

时间:2019-08-12 发布者: 访问量:3706

需要一个textbox只接受数字是很常见的要求,我介绍一种方法。

private void FirstSWTB_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar <= 47 || e.KeyChar >= 58) && (e.KeyChar != 8) &&(e.KeyChar != 46))
                e.Handled = true;
        }

这是用ascii码来进行控制的,0-9的ascii为48-57,小数点为46,退格为8。 
那么问题来了,e.Handled是个什么? 
e.Handled 是表示Gets or sets a value indicating whether the KeyPress event was handled.(MSDN)获取或是设置一个值,该值指示keypress事件是否被处理了。

这就让人很疑惑,什么叫keypress时间被处理呢?

后面有一段话If the event is not handled, it will be sent to the operating system for default processing. Set Handled to true to cancel the KeyPress event.(MSDN)如果这个事件没有被处理,他将会被送到操作系统进行默认处理,设置handled为true会取消这个keypress事件。 
也就是说,凡是keypress为true的时候,就不会触发按键事件,相当于没有按。
发布于
  用户评论
    生活编程