嗨,我希望程序在输入String时显示一条错误消息,我尝试过在线使用某些解决方案,但对我的解决方案不起作用,如果能为我解决问题,非常感谢。
//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;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
我认为在您的情况下,首先尝试将txtPrice.Text值转换为Double会更好。
这是十进制.tryparse的链接。
代码如下所示:
decimal price;
//Price must be numeric
if(!Decimal.TryParse(txtPrice.Text, out price))
{
MessageBox.Show("Price must be numeric", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPrice.Focus();
return;
}
//price must be a positive number
if(price <= 0)
{
MessageBox.Show("Price must be a positive number", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPrice.Focus();
return;
}
Run Code Online (Sandbox Code Playgroud)