如何验证文本框只接受c#windown应用程序中的数值? [英] How to validate textbox to accept only numeric values in c# windown application ?

查看:79
本文介绍了如何验证文本框只接受c#windown应用程序中的数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void txtPrinterNumber_KeyPress(object sender, KeyPressEventArgs e)
       {
           if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "\\d+"))
               e.Handled = true;

       }

推荐答案

private void txtPrinterNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
        (e.KeyChar != '.'))
    {
            e.Handled = true;
    }

    // only allow one decimal point
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
    {
        e.Handled = true;
    }
}


它可以完成 - 它并不复杂,只是烦人,因为你必须处理它防止粘贴添加alpha的地方。



更好的解决方案是使用NumericUpDown控件,它可以为你完成所有。



如果您打算手动执行此操作,请考虑查看TextChanged事件并使用Regex.Replace而不是IsMatch - 但不要忘记光标位置可能需要更正。
It can be done - it's not complex, it's just annoying, because you have to handle it in a number of places to prevent paste adding alpha as well.

The better solution is to use a NumericUpDown control, which does it all for you.

If you are going to do it manually, consider looking at the TextChanged event and using Regex.Replace instead of IsMatch - but don't forget the cursor position may need correcting.


这篇关于如何验证文本框只接受c#windown应用程序中的数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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