验证文本框是否仅包含数字

问题描述 投票:5回答:4

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

c# mysql exception try-catch
4个回答
17
投票

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

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

// Save parsedValue into the database

3
投票

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

  • 从标记视图切换到设计视图。
  • 现在单击设计视图,然后按Ctrl + Alt + X.
  • 从打开的工具箱中单击验证并在TextBox附近拖动比较验证器。
  • 右键单击compare验证器并选择属性,现在找到ErrorMessage并写入“Alert:Type only Number”。
  • 在控制验证中选择您的控件。
  • 在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;
    }
}

0
投票

你可以通过这种方式实现它

   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
    }     

0
投票
if(Int32.TryParse(textBox1.Text, out int value))
{
    // Here comes the code if numeric
}
else
{
    // Here comes the code if not numeric
}
© www.soinside.com 2019 - 2024. All rights reserved.