如果具有多个空文本框的语句

时间:2014-07-15 17:46:23

标签: c# if-statement textbox conditional-statements

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有人可以给我正确的代码。我想确保在输入数据时如果有一个空的文本框,系统将不会继续,除非它填充所有空白文本框:)

4 个答案:

答案 0 :(得分:5)

你有AND(&&),应该是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);
        }

答案 1 :(得分:1)

如果只有一个空文本框应被视为错误,那么您需要更改&& (AND)条件运算符|| (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);
}

答案 2 :(得分:1)

使用一点LINQ可能会更清楚:

var textBoxes = new TextBox[] { txtUserID, txtFN, txtMI, txtLN,
                                txtUsername, txtPassword, txtConfirm };

if (textBoxes.Any(tb => tb.Text == String.Empty))
{
    // Show the MessageBox
}

答案 3 :(得分:1)

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

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