将文本框输入限制为 C# 中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1935219/
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-06 21:59:42  来源:igfitidea点击:

Restricting textbox input to numbers in C#

c#

提问by ibrahim

I want to restrict a textbox to accept only numbers in C#. How do I do that?

我想限制一个文本框只接受 C# 中的数字。我怎么做?

回答by jay_t55

Have you tried the MaskedTextBox control in WinForms?

您是否尝试过 WinForms 中的 MaskedTextBox 控件?

回答by Adriaan Stander

Have a look at something like this

看看这样的

Masked C# TextBox Control

屏蔽 C# 文本框控件

回答by BFree

The most crude down and dirty way of doing it is doing something like this:

最粗暴和肮脏的做法是做这样的事情:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        this.textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
    }

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

}

You're still not safe with this approach, as users can still copy and paste non-numeric characters into the textbox. You still need to validate your data regardless.

这种方法仍然不安全,因为用户仍然可以将非数字字符复制并粘贴到文本框中。无论如何,您仍然需要验证您的数据。

回答by Bhaskar

You can use the FilterTextBoxof AJAX Control Toolkit. Using this you can allow/disallow any character type. This is quite flexible.

您可以使用AJAX Control Toolkit的FilterTextBox。使用它您可以允许/禁止任何字符类型。这是相当灵活的。

回答by eriksv88

From others have said before me, we have to almost know what you will use this in, WinForms, ASP.NET, Silverlight ...

从其他人在我之前说的,我们必须几乎知道你将在 WinForms、ASP.NET、Silverlight 中使用它......

But now I take a chance that it is WinForm:)

但现在我有机会看到它是 WinForm :)

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

回答by Michael Fitzpatrick

You can use the Microsoft.VisualBasic.Information.IsNumeric is numeric function. Just add the reference Microsoft.VisualBasic

您可以使用 Microsoft.VisualBasic.Information.IsNumeric 是数字函数。只需添加引用 Microsoft.VisualBasic

private void textBox1_Validating(object sender,
        System.ComponentModel.CancelEventArgs e) {
    if (!Microsoft.VisualBasic.Information.IsNumeric(textBox1.Text)) {
        e.Cancel = true;
    } else {
        // Do something here
    }
}

This allows the user to enter scientific notation which is not trivial to filter for.

这允许用户输入不容易过滤的科学记数法。

回答by blitzen

Not sure if this is the correct way, but it works for me, running it on the TextChanged event TextBox has:

不确定这是否是正确的方法,但它对我有用,在 TextChanged 事件 TextBox 上运行它具有:

    private void CoordinateValidation(object sender, TextChangedEventArgs e) {
        TextBox inputBox = e.OriginalSource as TextBox;
        inputBox.TextChanged -= CoordinateValidation;
        int caretPos = inputBox.CaretIndex;
        foreach (TextChange change in e.Changes) {
            if (inputBox.Text.Substring(change.Offset, change.AddedLength).Any(c => !ValidChars.Contains(c)) ||
                inputBox.Text.Count(c => c == '.') > 1 ||
                (inputBox.Text.Length > 0 && inputBox.Text.Substring(1).Contains('-'))) {
                inputBox.Text = inputBox.Text.Remove(change.Offset, change.AddedLength);
                caretPos -= change.AddedLength;
            }
        }
        inputBox.CaretIndex = caretPos;
        inputBox.TextChanged += CoordinateValidation;
    }

回答by Mark

This may not be the best way, but works ok for WPF TextBox...

这可能不是最好的方法,但适用于 WPF TextBox ...

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        string originalText = ((TextBox)sender).Text.Trim();
        if (originalText.Length>0)
        {
            int inputOffset = e.Changes.ElementAt(0).Offset;
            char inputChar = originalText.ElementAt(inputOffset);
            if (!char.IsDigit(inputChar))
            {
                ((TextBox)sender).Text = originalText.Remove(inputOffset, 1);
            }
        }
    }

回答by user1797919

has some bugs but easy way :D

有一些错误,但方法很简单:D

 private void textbox1_TextChanged(object sender, EventArgs e)
        { 
            char[] originalText = textbox1.Text.ToCharArray();
            foreach (char c in originalText)
            {
                if (!(Char.IsNumber(c)))
                {
                    textbox1.Text = textbox1.Text.Remove(textbox1.Text.IndexOf(c));
                    lblError.Visible = true;
                }
                else
                    lblError.Visible = false;
            }
            textbox1.Select(textbox1.Text.Length, 0);
        }

回答by Tijo Tom

Have a look at the below code

看看下面的代码

private void txtbox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        const char Delete = (char)8;
        e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
    }

This will be helpful but users can Copy and Paste characters :-)

这会很有帮助,但用户可以复制和粘贴字符:-)