解析空字符串int.Parse
会给你一个例外。我的意思是:int.Parse("")
结果:Input string was not in a correct format.
要解决该问题,请TryParse
改用:
int ina;
int inb;
if (int.TryParse(txttea.Text, out ina) && int.TryParse(txtcoffee.Text, out inb))
{
//Ok, more code here
}
else
{
//got a wrong format, MessageBox.Show or whatever goes here
}
当然,您也可以单独测试它们[先 ina 然后 inb,反之亦然]:
int ina;
if (int.TryParse(txttea.Text, out ina))
{
int inb;
if (int.TryParse(txtcoffee.Text, out inb))
{
//Ok, more code here
}
else
{
//got a wrong format, MessageBox.Show or whatever goes here
}
}
else
{
//got a wrong format, MessageBox.Show or whatever goes here
}
现在,关于比较空字符串,如果您想要在两者都为空时的消息:
if(this.txttea.Text == "" && this.txtcoffee.Text == "")
{
MessageBox.Show("select a item");
txttea.Focus();
}
另一方面,如果您想在 AT LEAST ONE 为空时收到消息:
if(this.txttea.Text == "" || this.txtcoffee.Text == "")
{
MessageBox.Show("select a item");
txttea.Focus();
}