如何使一个文本框,只接受数字? [英] How do I make a textbox that only accepts numbers?

查看:222
本文介绍了如何使一个文本框,只接受数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想只接受整数值的文本框控件的Windows窗体应用程序。在过去,我已经超载的关键preSS事件,只是去掉其中不符合规范的字符做这种验证。我看着M​​askedTextBox控件,但我想一个可能或许与常规EX pression工作,或依赖于其他控件的值更通用的解决方案。

I have a windows forms app with a textbox control that I want to only accept integer values. In the past I've done this kind of validation by overloading the KeyPress event and just removing characters which didn't fit the specification. I've looked at the MaskedTextBox control but I'd like a more general solution that could work with perhaps a regular expression, or depend on the values of other controls.

在理想情况下,这将表现使得pressing一个非数字字符要么产生任何结果或立即向用户提供关于该无效字符来提供反馈。

Ideally this would behave such that pressing a non numeric character would either produce no result or immediately provide the user with feedback about the invalid character.

推荐答案

有两个选项:

  1. 使用一个<一个href="http://msdn.microsoft.com/en-us/library/system.windows.forms.numericupdown(v=vs.110).aspx"><$c$c>NumericUpDown代替。做的NumericUpDown过滤对你来说,这是很好的。当然,它也给你的用户能够击中向上和向下箭头键盘上的增加和减少电流值。

  1. Use a NumericUpDown instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.

处理适当的键盘事件,以prevent什么,但数字输入。我有一个标准的文本框与此两个事件处理程序的成功:

Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox:

private void textBox1_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;
    }
}

您可以删除检查(以及随后的检查多个 )如果你的文本框不应该允许小数点。你也可以添加一个检查 - 。如果你的文本框应当允许负值

You can remove the check for '.' (and the subsequent check for more than one '.') if your TextBox shouldn't allow decimal places. You could also add a check for '-' if your TextBox should allow negative values.

如果你想限制用户对数字的号码,使用: textBox1.MaxLength = 2; //这将允许用户只输入2位数字

If you want to limit the user for number of digit, use: textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits

这篇关于如何使一个文本框,只接受数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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