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

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

问题描述

我有一个带有文本框控件的 Windows 窗体应用程序,我只想接受整数值.在过去,我通过重载 KeyPress 事件并仅删除不符合规范的字符来完成这种验证.我查看了 MaskedTextBox 控件,但我想要一个更通用的解决方案,它可以使用正则表达式,或者取决于其他控件的值.

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.

理想情况下,按下非数字字符将不会产生任何结果或立即向用户提供有关无效字符的反馈.

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. 使用 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.

处理适当的键盘事件以防止除数字输入之外的任何内容.我在标准 TextBox 上使用这两个事件处理程序取得了成功:

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;
    }
}

如果您的 TextBox 不允许使用小数位,您可以删除对 '.' 的检查(以及随后对多个 '.' 的检查).如果您的 TextBox 应该允许负值,您还可以添加对 '-' 的检查.

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天全站免登陆