验证文本框以仅允许数值

Wiz*_*ard 5 c# validation

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

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

我在使用中读到了这个

txtHomePhone.Text
Run Code Online (Sandbox Code Playgroud)

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

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

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

Pic*_*are 8

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

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Tre*_*ley 7

我假设你在这里使用Windows Forms,看一下MaskedTextBox.它允许您指定字符的输入掩码.

txtHomePhone.Mask = "##### ### ###";
Run Code Online (Sandbox Code Playgroud)

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

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


Dav*_*New 5

要检查是否已输入数值,您可以使用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.
Run Code Online (Sandbox Code Playgroud)

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