c# - 验证文本框以仅允许数值

标签 c# validation

<分区>

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

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

我在使用中阅读了这个

txtHomePhone.Text

我想我需要的是某种数字但无法让它工作

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

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

最佳答案

由于 txtHomePhone 代表一个 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
    }
}

通知:The following character (which is not visible) represents a backspace.
注意:您始终可以使用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;
    }
}

谢谢,
希望这对您有所帮助:)

关于c# - 验证文本框以仅允许数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13253198/

相关文章:

c# - 将字符串转换为十进制? (可为空的十进制)通过扩展方法

forms - ReCaptcha 无效 + CodeIgniter 表单助手 = 表单数据丢失

jquery post codeigniter 验证

php - 如果数据库出现故障,如何保留动态创建的输入字段值?

PHP 在验证错误后保留输入的值

c# - 如何打开最大化的 Internet Explorer?

c# - 扩展 Asp.Net Identity IsInRole() 方法

c# - 在 c sharp 中获取和设置属性不工作

c# - 如何使用 C#/.NET 在 Windows 中使用拨号 (RAS) 连接?

javascript - 使用 UI Utils 进行 Angular 表单验证