带有多个空文本框的If语句

本文关键字:If 语句 文本 | 更新日期: 2023-09-27 18:13:15

if (txtUserID.Text == String.Empty && 
    txtFN.Text == String.Empty && 
    txtMI.Text == String.Empty && 
    txtLN.Text == String.Empty && 
    txtUsername.Text == String.Empty && 
    txtPassword.Text == String.Empty && 
    txtConfirm.Text == String.Empty)
{
    XtraMessageBox.Show("All fields are required!", 
                        "Warning", 
                        MessageBoxButtons.OK, 
                        MessageBoxIcon.Warning);
}

Hello Guys谁能给我正确的代码这个。我想看到它,如果有一个空的文本框,当输入数据时,系统将不会继续,除非它填充所有的空白文本框:)

带有多个空文本框的If语句

你(,,),应该或(| |)

if (txtUserID.Text == String.Empty || txtFN.Text == String.Empty || txtMI.Text == String.Empty || txtLN.Text == String.Empty || txtUsername.Text == String.Empty || txtPassword.Text == String.Empty || txtConfirm.Text == String.Empty)
        {
            XtraMessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

如果只有一个空文本框应该被认为是错误的,那么你需要改变&&(AND)条件运算符to || (OR)

if (txtUserID.Text == String.Empty || 
   txtFN.Text == String.Empty || 
   txtMI.Text == String.Empty || 
   txtLN.Text == String.Empty || 
   txtUsername.Text == String.Empty || 
   txtPassword.Text == String.Empty || 
   txtConfirm.Text == String.Empty)
{
  XtraMessageBox.Show("All fields are required!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}

用一点LINQ:

可能会更清楚
var textBoxes = new TextBox[] { txtUserID, txtFN, txtMI, txtLN,
                                txtUsername, txtPassword, txtConfirm };
if (textBoxes.Any(tb => tb.Text == String.Empty))
{
    // Show the MessageBox
}

如果所有文本框都在同一容器中,则可以使用:

if(Controls.OfType<TextBox>().Any(t => t.Text == ""))
{
   //Show error message
}