C# 验证文本框以仅允许数字值

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

Validating a textbox to allow only numeric values

c#validation

提问by Wizard

Possible Duplicate:
How do I make a textbox that only accepts numbers?

可能的重复:
如何制作只接受数字的文本框?

I have a phone number that I wish to store as a string.

我有一个电话号码,希望将其存储为字符串。

I read this in using

我在使用中读到了这个

txtHomePhone.Text

What I think I need is some kind of is numeric but can't get it working

我认为我需要的是某种数字但无法使其正常工作

if (txtHomePhone.Text == //something.IsNumeric)
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

What is the best way to allow only numeric values to be entered?

只允许输入数值的最佳方法是什么?

采纳答案by Picrofo Software

Since txtHomePhonerepresents a TextBox, you may use the KeyPressevent to accept the characters you would like to allow and reject what you would not like to allow in txtHomePhone

由于txtHomePhone代表 a TextBox,您可以使用该KeyPress事件接受您希望允许的字符并拒绝您不希望允许的字符txtHomePhone

Example

例子

public Form1()
{
    InitializeComponent();
    txtHomePhone.KeyPress += new KeyPressEventHandler(txtHomePhone_KeyPress);
}
private void txtHomePhone_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true; //Reject the input
    }
}

Notice: The following character (which is not visible) represents a backspace.
Notice: You may always allow or disallow a particular character using e.Handled.
Notice: You may create a conditional statement if you would like to use -, , (or )only once. I would recommend you to use Regular Expressions if you would like to allow these characters to be entered in a specific position.

注意以下字符(不可见)表示退格。
注意:您始终可以使用 来允许或禁止特定字符e.Handled
注意:如果您想使用、或仅使用一次-,您可以创建一个条件语句。如果您希望允许在特定位置输入这些字符,我建议您使用正则表达式。()

Example

例子

if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '') //The  character represents a backspace
{
    e.Handled = false; //Do not reject the input
}
else
{
    if (e.KeyChar == ')' && !txtHomePhone.Text.Contains(")"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '(' && !txtHomePhone.Text.Contains("("))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == '-' && !textBox1.Text.Contains("-"))
    {
        e.Handled = false; //Do not reject the input
    }
    else if (e.KeyChar == ' ' && !txtHomePhone.Text.Contains(" "))
    {
        e.Handled = false; //Do not reject the input
    }
    else
    {
        e.Handled = true;
    }
}

Thanks,
I hope you find this helpful :)

谢谢,
我希望你觉得这有帮助:)

回答by Blachshma

Try this

尝试这个

if (!txtHomePhone.Text.All(c=> Char.IsNumber(c)))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

回答by Dave New

To check to see if a numeric value has been entered, you can use Integer.TryParse

要检查是否已输入数值,您可以使用 Integer.TryParse

int num;
bool isNum = Integer.TryParse(txtHomePhone.Text.Trim(), out num);

if (!isNum)
    //Display error
else
    //Carry on with the rest of program ie. Add Phone number to program.

BUT remember that telephone numbers aren't necessarily only numeric. Refer to Trevor Pilley answer for a masked textbox.

但请记住,电话号码不一定只是数字。有关蒙面文本框,请参阅 Trevor Pilley 的答案。

回答by Trevor Pilley

I'm assuming that you are using Windows Forms here, have a look at the MaskedTextBox. It allows you to specify an input mask of characters.

我假设您在这里使用 Windows 窗体,请查看MaskedTextBox。它允许您指定字符的输入掩码。

txtHomePhone.Mask = "##### ### ###";

Since this allows you to restrict the input values, you can safely parse the value to an integer.

由于这允许您限制输入值,因此您可以安全地将值解析为整数。

Note: If you are using WPF, I don't think there is a MaskedTextBox in the base libraries, however there are extensions available on NuGetwhich may provide similar functionality.

注意:如果您使用 WPF,我认为基础库中没有 MaskedTextBox,但是NuGet上有可用的扩展,它们可能提供类似的功能。

回答by Mike Rodey

Usually I would use Integer.TryParse as davenewza recommended, but another alternative is to use the VisualBasic IsNumeric function from C#.

通常我会像 davenewza 推荐的那样使用 Integer.TryParse,但另一种选择是使用 C# 中的 VisualBasic IsNumeric 函数。

Add a reference to the Microsoft.VisualBasic.dll file and then use the following code.

添加对 Microsoft.VisualBasic.dll 文件的引用,然后使用以下代码。

if (Microsoft.VisualBasic.Information.IsNumeric(txtHomePhone.Text))
{
    //Display error
}
else
{
    //Carry on with the rest of program ie. Add Phone number to program.
}

回答by Wizard

The best way I've found to do this is to only allow the user to enter the numeric keys into the text box, thanks for your help.

我发现最好的方法是只允许用户在文本框中输入数字键,感谢您的帮助。