【问题标题】:Validating whether a textbox contains only numbers验证文本框是否仅包含数字
【发布时间】:2013-03-02 05:09:15
【问题描述】:

所以我有一个想法,因为我发现很难为 txtbox 编写代码,它只允许使用 c# 在 mysql 中使用整数而不是字母。我的计划是为什么不将数据库列设置为整数而不是典型的 varchar,如果你放了一个字母,它当然会变成异常,所以在这种情况下,我想捕获异常并提示一个消息框说“请仅输入整数” .你怎么看?

【问题讨论】:

  • 您不需要在标题中复制标签(尤其是在“我正在使用 C#?”的问题形式中,就好像您不知道您使用什么语言一样)。旁注:您的实际问题似乎是“如何验证字符串是否为整数以存储在数据库中”...
  • 好的,我会改写它,但这就是我想问的。

标签: c# mysql exception try-catch


【解决方案1】:

为您计划在其中存储的内容使用正确的列数据类型是个好主意,但检查字符串是否仅包含数字非常容易 - 只需解析并查看是否返回错误:

int parsedValue;
if (!int.TryParse(textBox.Text, out parsedValue))
{
    MessageBox.Show("This is a number only field");
    return;
}

// Save parsedValue into the database

【讨论】:

  • 您的代码对我来说是新的,因为我之前尝试过不同的代码,但它们不起作用。但无论如何,我会试试你的。谢谢
  • 除了这些检查之外,我仍然建议将您的列更改为整数列 - 更好地提高数据完整性、效率和磁盘空间...
【解决方案2】:

Visual Studio 内置了对此的支持(您也可以通过编码来实现)。这是你需要做的:

  • 从标记视图切换到设计视图。
  • 现在单击设计视图并按 Ctrl+Alt+X
  • 从打开的工具箱中点击验证并将比较验证器拖到您的TextBox 附近。
  • 右键单击比较验证器并选择属性,现在找到ErrorMessage 并写下“警报:仅输入数字”。
  • 在要验证的控件中选择您的控件。
  • 在 Operator 中选择 DataTypeCheck,在 Type 中选择 Integer。

也可以通过编码获得:

protected void Button1_Click(object sender, EventArgs e)
{
    int i;
    if (!int.TryParse(textBox.Text, out i))
    {
        Label.Text = "This is a number only field";
        return;
    }
}

【讨论】:

    【解决方案3】:
    if(Int32.TryParse(textBox1.Text, out int value))
    {
        // Here comes the code if numeric
    }
    else
    {
        // Here comes the code if not numeric
    }
    

    【讨论】:

    • 请在 TryParse 函数中添加一些描述。不仅仅是一个代码块
    • 正是我想要的,并且按预期工作。谢谢。
    【解决方案4】:

    你可以这样实现

       int outParse;
    
       // Check if the point entered is numeric or not
       if (Int32.TryParse(propertyPriceTextBox.Text, out outParse) && outParse)
        {
           // Do what you want to do if numeric
        }
       else
        {
           // Do what you want to do if not numeric
        }     
    

    【讨论】:

    • 这甚至不能编译。不能对整数使用布尔运算符 (&& outParse)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    相关资源
    最近更新 更多