C# 如果三个文本框均为空,则don';我什么也不做
如果三个文本框都是空的,不要做任何事情。然而下面的代码显示这三个也都是空的。但我不想要这个C# 如果三个文本框均为空,则don';我什么也不做,c#,winforms,if-statement,C#,Winforms,If Statement,如果三个文本框都是空的,不要做任何事情。然而下面的代码显示这三个也都是空的。但我不想要这个 var textBoxes = new [] { new { txb = txtUserName, name = "txtUserName" }, new { txb = txtPassw, name = "txtPassw" }, new { txb = txtDatabase , name = "txtDatabase " } }; var empty = text
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,这通常被认为是比
==“”更好的做法。
因为您处理的是文本框(其字符串从不为null),所以使用旧的比较仍然可以,但是。谢谢您的回复,但是如果所有文本框都是空的,我不想显示任何消息。我如何在C#中使用Windows窗体应用程序。您正在寻找IEnumerable.all()?if(empty.any()&&&!textboxs.all(x=>String.IsWhitespaceOrEmpty(x.txb.text)){代码>在这里也起作用:)它说字符串dosent包含IsWhitespaceOrEmptystill的定义如果这三个都为空,则将收到消息如果您使用的是较旧版本的.Net,则无法使用它,请使用IsNullOrEmpty代替TextBox。长度显然为3,什么是空的。当它们都为空时计数?如果不是3,你可能有一些文字在那里。。。我没有看到我的代码中有任何错误,如果问题仍然存在,请告诉我。
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)));
}