如果三个文本框都是空的,不要做任何事情
本文关键字:任何事 三个 文本 如果 | 更新日期: 2023-09-27 17:51:15
如果三个文本框都为空,则不做任何操作。然而,下面的代码显示这三个都是空的。但我不想这样。
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)));
}
修改@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,这通常被认为是比== "".
更好的实践,因为您正在处理文本框(其字符串永远不会为空),您仍然可以使用旧的比较,然而。
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)));
}