C#-我想在ConvertToDecimal函数中输入字符串时显示一个错误
您好,我想程序显示一个错误消息,当我输入一个字符串,我曾试图使用一些在线解决方案,但它不在我的工作,如果能为我解决,将非常感谢非常感谢C#-我想在ConvertToDecimal函数中输入字符串时显示一个错误,c#,winforms,C#,Winforms,您好,我想程序显示一个错误消息,当我输入一个字符串,我曾试图使用一些在线解决方案,但它不在我的工作,如果能为我解决,将非常感谢非常感谢 //Price must be numeric if(txtPrice.Text == String.txtPrice)//There is an error on this I can't figure it out { MessageBox.Show("Price must be numeric",
//Price must be numeric
if(txtPrice.Text == String.txtPrice)//There is an error on this I can't figure it out
{
MessageBox.Show("Price must be numeric", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPrice.Focus();
return;
}
//price must be a positive number
if( Convert.ToDecimal(txtPrice.Text) <= 0)
{
MessageBox.Show("Price must be a positive number", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPrice.Focus();
return;
}
//价格必须是数字
如果(txtPrice.Text==String.txtPrice)//这上面有一个错误,我想不出来
{
Show(“价格必须是数字”,“错误!”,MessageBoxButtons.OK,MessageBoxIcon.Error);
txtPrice.Focus();
返回;
}
//价格必须是正数
如果(Convert.ToDecimal(txtPrice.Text)使用此代码
try{
double x = Convert.ToDecimal(txtPrice.Text)
}
catch(Exeption e){
MessageBox.Show("Price must be a positive number", "Error!",
MessageBoxButtons.OK,MessageBoxIcon.Error);
}
我认为在您的情况下,最好先尝试将txtPrice.Text值转换为Double
这里有到的链接
代码如下所示:
十进制价格;
//价格必须是数字
如果(!Decimal.TryParse(txtPrice.Text,out price))
{
Show(“价格必须是数字”,“错误!”,MessageBoxButtons.OK,MessageBoxIcon.Error);
txtPrice.Focus();
返回;
}
//价格必须是正数
如果(price)在用代码回答问题时使用Decimal.TryParse,最好添加一个解释,说明它为什么回答原始问题。此外,此代码应该缩进,并捕获一个比基类异常
更少的一般错误。