C# 如何制作只接受数字的文本框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/463299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:24:38  来源:igfitidea点击:

How do I make a textbox that only accepts numbers?

c#.netwinformstextbox

提问by Mykroft

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.

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

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.

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

采纳答案by Matt Hamilton

Two options:

两种选择:

  1. Use a NumericUpDowninstead. 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.

  2. 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;
        }
    }
    
  1. 使用 aNumericUpDown代替。NumericUpDown 为您进行过滤,这很好。当然,它也让您的用户能够点击键盘上的向上和向下箭头来增加和减少当前值。

  2. 处理适当的键盘事件以防止除数字输入之外的任何事情。我在标准 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.

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

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

如果要限制用户的位数,请使用: textBox1.MaxLength = 2; // this will allow the user to enter only 2 digits

回答by Perpetualcoder

you could use TextChanged/ Keypress event, use a regex to filter on numbers and take some action.

您可以使用TextChanged/ Keypress 事件,使用正则表达式过滤数字并采取一些措施。

回答by Andrew Kennan

Try a MaskedTextBox. It takes a simple mask format so you can limit the input to numbers or dates or whatever.

尝试一个MaskedTextBox。它采用简单的掩码格式,因此您可以将输入限制为数字或日期或其他任何内容。

回答by Anthony D

I am assuming from context and the tags you used that you are writing a .NET C# app. In this case, you can subscribe to the text changed event, and validate each key stroke.

我根据上下文和您使用的标签假设您正在编写 .NET C# 应用程序。在这种情况下,您可以订阅文本更改事件,并验证每个击键。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "[^0-9]"))
    {
        MessageBox.Show("Please enter only numbers.");
        textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    }
}

回答by benPearce

Take a look at Input handling in WinForm

看一看WinForm中的输入处理

I have posted my solution which uses the ProcessCmdKey and OnKeyPress events on the textbox. The comments show you how to use a Regex to verify the keypress and block/allow appropriately.

我已经发布了我的解决方案,它在文本框中使用 ProcessCmdKey 和 OnKeyPress 事件。注释向您展示了如何使用正则表达式来验证按键并适当地阻止/允许。

回答by GvS

I have made something for this on CodePlex.

我在CodePlex 上为此做了一些事情。

It works by intercepting the TextChanged event. If the result is a good number it will be stored. If it is something wrong, the last good value will be restored. The source is a bit too large to publish here, but here is a link to the classthat handles the core of this logic.

它通过拦截 TextChanged 事件来工作。如果结果是一个好的数字,它将被存储。如果出现问题,将恢复上次良好的值。源代码有点大,无法在此处发布,但这里是处理此逻辑核心的类的链接

回答by BFree

And just because it's always more fun to do stuff in one line...

仅仅因为在一行中做事情总是更有趣......

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

NOTE: This DOES NOT prevent a user from Copy / Paste into this textbox. It's not a fail safe way to sanitize your data.

注意:这不会阻止用户复制/粘贴到此文本框中。这不是清理数据的万无一失的方法。

回答by yardape

Sorry to wake the dead, but I thought someone might find this useful for future reference.

很抱歉唤醒死者,但我认为有人可能会发现这对将来的参考很有用。

Here is how I handle it. It handles floating point numbers, but can easily be modified for integers.

这是我如何处理它。它处理浮点数,但可以很容易地修改为整数。

Basically you can only press 0- 9and .

基本上你只能按0- 9

You can only have one 0before the .

.之前只能有一个0

All other characters are ignored and the cursor position maintained.

忽略所有其他字符并保持光标位置。

    private bool _myTextBoxChanging = false;

    private void myTextBox_TextChanged(object sender, EventArgs e)
    {
        validateText(myTextBox);
    }

    private void validateText(TextBox box)
    {
        // stop multiple changes;
        if (_myTextBoxChanging)
            return;
        _myTextBoxChanging = true;

        string text = box.Text;
        if (text == "")
            return;
        string validText = "";
        bool hasPeriod = false;
        int pos = box.SelectionStart;
        for (int i = 0; i < text.Length; i++ )
        {
            bool badChar = false;
            char s = text[i];
            if (s == '.')
            {
                if (hasPeriod)
                    badChar = true;
                else
                    hasPeriod = true;
            }
            else if (s < '0' || s > '9')
                badChar = true;

            if (!badChar)
                validText += s;
            else
            {
                if (i <= pos)
                    pos--;
            }
        }

        // trim starting 00s
        while (validText.Length >= 2 && validText[0] == '0')
        {
            if (validText[1] != '.')
            {
                validText = validText.Substring(1);
                if (pos < 2)
                    pos--;
            }
            else
                break;
        }

        if (pos > validText.Length)
            pos = validText.Length;
        box.Text = validText;
        box.SelectionStart = pos;
        _myTextBoxChanging = false;
    }

Here is a quickly modified int version:

这是一个快速修改的 int 版本:

    private void validateText(TextBox box)
    {
        // stop multiple changes;
        if (_myTextBoxChanging)
            return;
        _myTextBoxChanging = true;

        string text = box.Text;
        if (text == "")
            return;
        string validText = "";
        int pos = box.SelectionStart;
        for (int i = 0; i < text.Length; i++ )
        {
            char s = text[i];
            if (s < '0' || s > '9')
            {
                if (i <= pos)
                    pos--;
            }
            else
                validText += s;
        }

        // trim starting 00s 
        while (validText.Length >= 2 && validText.StartsWith("00")) 
        { 
            validText = validText.Substring(1); 
            if (pos < 2) 
                pos--; 
        } 

        if (pos > validText.Length)
            pos = validText.Length;
        box.Text = validText;
        box.SelectionStart = pos;
        _myTextBoxChanging = false;
    }

回答by newguy

int Number;
bool isNumber;
isNumber = int32.TryPase(textbox1.text, out Number);

if (!isNumber)
{ 
    (code if not an integer);
}
else
{
    (code if an integer);
}

回答by Davit Tvildiani

You can use the TextChangedevent

您可以使用该TextChanged事件

private void textBox_BiggerThan_TextChanged(object sender, EventArgs e)
{
    long a;
    if (! long.TryParse(textBox_BiggerThan.Text, out a))
    {
        // If not int clear textbox text or Undo() last operation
        textBox_LessThan.Clear();
    }
}