Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 验证文本框是否仅包含数字_C#_Mysql_Exception_Try Catch - Fatal编程技术网

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

C# 验证文本框是否仅包含数字,c#,mysql,exception,try-catch,C#,Mysql,Exception,Try Catch,所以我有了一个想法,因为我发现很难为txtbox编写一个代码,在mysql中使用c#只允许整数而不允许字母。我的计划是,为什么不将数据库列设置为integer而不是典型的varchar,如果您输入一个字母,它当然会变成和exception,因此在这种情况下,我希望捕获异常并提示一个消息框说“请只输入integer”。您认为呢?对于您计划存储在其中的内容,使用正确的列数据类型是一个好主意,但是检查字符串是否只包含数字非常容易,只需解析并查看是否返回错误: int parsedValue; if (

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

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

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

// Save parsedValue into the database

你可以这样做

   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
    }     

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

  • 从标记视图切换到设计视图
  • 现在单击设计视图并按Ctrl+Alt+X
  • 从打开的工具箱中,单击验证并将比较验证程序拖到
    文本框附近
  • 右键单击比较验证器并选择属性,现在找到
    ErrorMessage
    并写入“警报:仅键入数字”
  • 在要验证的控件中选择您的控件
  • 在运算符中选择DataTypeCheck,在类型中选择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;
    }
}

您不需要在标题中重复标记(尤其是以问题“我正在使用C#?”的形式,好像您不知道您使用的是什么语言)。旁注:您实际的问题似乎是“如何验证字符串是否为整数以存储在DB中”…好的,我会重新措辞,但这正是我想问的。您的代码对我来说是新的,因为我尝试过不同的代码,但它们不起作用。但无论如何,我会试试你的。感谢您除了这些检查之外,我仍然建议您将列更改为整数列-更好地保证数据完整性、效率和磁盘空间…这甚至不会编译。不能对整数(
&&outParse
)使用布尔运算符。请为TryParse函数添加一些说明。不仅仅是一个代码块,这正是我所寻找的,而且工作正常。非常感谢。
if(Int32.TryParse(textBox1.Text, out int value))
{
    // Here comes the code if numeric
}
else
{
    // Here comes the code if not numeric
}