如果所有三个文本框都为空,则不执行任何操作

时间:2014-03-22 05:16:58

标签: c# winforms if-statement

如果所有三个文本框都为空,则不执行任何操作。但是下面的代码显示所有三个都是空的。但我不想要这个。

     var textBoxes = new [] {
    new { txb = txtUserName, name = "txtUserName" },
    new { txb = txtPassw, name = "txtPassw" },
    new { txb = txtDatabase , name = "txtDatabase " }
};

var empty = textBoxes.Where(x => x.txb.Text == "").ToList();

if(empty.Any())
{
    MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}

2 个答案:

答案 0 :(得分:1)

修改@ MarcinJuraszek的答案:

var textBoxes = new [] {
    new { txb = txtUserName, name = "txtUserName" },
    new { txb = txtPassw, name = "txtPassw" },
    new { txb = txtDatabase , name = "txtDatabase " }
};

var empty = textBoxes.Where(x => String.IsWhitespaceOrEmpty(x.txb.Text)).ToList();

if(empty.Any() && empty.Count != textboxes.Length)
{
    MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}

如果所有字符串都为空,我添加了额外的检查以不显示消息框。我还改变了比较以使用IsWhitespaceOrEmpty,以防你有一堆空格(通常是无效的输入)。你也可以使用IsNullOrEmpty,这通常被认为是比== "".更好的做法因为你正在处理文本框(其字符串永远不为空),你仍然可以使用旧的比较。

答案 1 :(得分:0)

var textBoxes = new [] {
    new { txb = txtUserName, name = "txtUserName" },
    new { txb = txtPassw, name = "txtPassw" },
    new { txb = txtDatabase , name = "txtDatabase " }
};

var empty = textBoxes.Where(x => x.txb.Text == "").ToList();

if(empty.Any())
{
    MessageBox.Show("Please enter " + String.Join(" and ", empty.Select(x => x.name)));
}