繁体   English   中英

在C#中正确使用逻辑运算符

[英]Correct use of logical operator in C#

我有以下If块,它在按下表单对象上的命令按钮时运行。 这应该仅检查一下上述四个文本框是否为空,如果显示为空,则显示一个消息框,然后退出该过程,以便用户可以更正字段并继续。

以下是相关代码:

 if (string.IsNullOrWhiteSpace(txtName.ToString()) || 
     string.IsNullOrWhiteSpace(txtID.ToString()) ||
     string.IsNullOrWhiteSpace(txtSalary.ToString()) ||
     string.IsNullOrWhiteSpace(txtERR.ToString()))
 {
  MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
  return;
 }

我将所有文本字段留为空白,甚至尝试在其中添加空格字符,但条件代码未执行。 由于代码未执行,因此我假设我的if语句出了点问题,也许我未使用'or'运算符|| 正确吗? 任何帮助表示赞赏。

如果要检查文本框,则需要从文本框中获取文本。

 if (string.IsNullOrWhiteSpace(txtName.Text) || ... 


作为一点好处,您也可以这样写:

if(new [] {txtName, txtID, txtSalary, txtERR}
  .Any(tb => string.IsNullOrWhiteSpace(tb.Text)))
{
   MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
   return;
}

您应该使用TextBox Text属性。 ToString方法返回字符串“ System.Windows.Forms.TextBoxBase”。 该字符串显然绝不能为空或为null。

if (string.IsNullOrWhiteSpace(txtName.Text) || 
 string.IsNullOrWhiteSpace(txtID.Text) ||
 string.IsNullOrWhiteSpace(txtSalary.Text) ||
 string.IsNullOrWhiteSpace(txtERR.Text)) 
 {
  MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
  return;
 }

如果控件的txtName,txtID等名称,则需要引用.Text属性。 尝试以下类似代码段的方法:

if (string.IsNullOrWhiteSpace(txtName.Text) || 
     string.IsNullOrWhiteSpace(txtID.Text) ||
     string.IsNullOrWhiteSpace(txtSalary.Text) ||
     string.IsNullOrWhiteSpace(txtERR.Text))
 {
  MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
  return;
 }

TextBox.ToString()将返回TextBox的类型-因此,它永远不会是NullOrWhiteSpace 您想要的是检查Text属性的内容,如下所示:

if (string.IsNullOrWhiteSpace(txtName.Text || 
 string.IsNullOrWhiteSpace(txtID.Text) ||
 string.IsNullOrWhiteSpace(txtSalary.Text) ||
 string.IsNullOrWhiteSpace(txtERR.Text))
 {
      MessageBox.Show("One or more text fields are empty or hold invalid data, please correct this to continue","Data Error",MessageBoxButtons.OK);
      return;
 }

我不使用IsNullOrWhiteSpace进行这种测试,相反,我更喜欢使用IsNullOrEmpty

尝试这个:

if (string.IsNullOrEmpty(txtName.Text)||...)
{...

或者txtName返回TEXT对象...然后尝试

if (string.IsNullOrEmpty(txtName.Text.toString())||...)
{...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM