试图过滤TextBox输入 [英] Trying to filter TextBox input

查看:58
本文介绍了试图过滤TextBox输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写将我的文本框输入限制为数字0-9的代码。但是,当我按下像w或g这样的字母键时,我会在文本框中看到它。



有谁可以看到为什么我的代码不起作用?



谢谢...



I'm trying to write code that will limit my textbox input to digits 0-9. However, when I press an alpha key like w or g I see it in the textbox.

Can anyone see why my code below doesn't work?

Thanks...

private Boolean IsNumberKey(Keys inKey)
{
    if (inKey >= Keys.D0 && inKey <= Keys.D9)
    {
        return true;
    }
    else
    {
        return false;
    }
}
private void txtBoxGetUserInput_KeyDown(object sender, KeyEventArgs e)
{
    if (IsNumberKey(e.KeyCode))
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = false;
    }
}

推荐答案

更好:

Better:
private void txtBoxGetUserInput_KeyDown(object sender, KeyEventArgs e)
{
    if (!IsNumberKey(e.KeyCode))
    {
        e.Handled = true;
    }
}





:)



或事件更好:





:)

[edit]Or event better:

private void txtBoxGetUserInput_KeyPress(object sender, KeyPressEventArgs e)
{
   if (!char.IsNumber(e.KeyChar)) {
      e.Handled = true;
   }
}



(如果你选择这个,请删除上一个事件处理程序)。

它会重新分析过滤掉非数字字符(而以前的版本只检查密钥,而不是真正输入的字符)。

[/ edit]


(but remove the previous event handler if you choose this one).
It will reaaly filter out non-numeric characters (whereas the previous version only check for the key, not the real entered character).
[/edit]


这篇关于试图过滤TextBox输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆