[英]how to compare two text box and if both is empty how to print a message box in c#
我在这里比较两个文本框,如果都为空,则尝试打印错误消息
int ina=int.Parse(txttea.Text);
int inb = int.Parse(txtcoffee.Text);
int inc=0, ind=0;
if(this.txttea.Text=="" && this.txtcoffee.Text=="")
{
MessageBox.Show("select a item");
txttea.Focus();
}
您需要||
代替&&
在行中:
if(this.txttea.Text=="" && this.txtcoffee.Text=="")
注意:问题与标题不符。
您的问题是如何验证TextBox
是空白还是空白 。
如果您使用的是.Net 3.5或更高版本,则最好使用String.IsNullOrWhiteSpace Method
来解决此问题
if(string.IsNullOrWhiteSpace(txttea.Text) ||
string.IsNullOrWhiteSpace(txtcoffee.Text))
{
MessageBox.Show("select a item");
txttea.Focus();
return;
}
以下内容应为以下内容,请修改您的问题以匹配以下提供的答案
int ina=int.Parse(txttea.Text);
int inb = int.Parse(txtcoffee.Text);
int inc=0, ind=0;
if(this.txttea.Text=="" || this.txtcoffee.Text=="")
{
MessageBox.Show("select an item");
txttea.Focus();
}
用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();
}
另一方面,如果要在“至少一个为空”时显示消息:
if(this.txttea.Text == "" || this.txtcoffee.Text == "")
{
MessageBox.Show("select a item");
txttea.Focus();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.