Reputation: 41
If all three textboxes are empty don't do anything. However below code shows all three are empty too. But I don't want this.
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)));
}
Upvotes: 0
Views: 95
Reputation: 61349
A modification of @MarcinJuraszek's answer:
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)));
}
I added an additional check to not display the message box if ALL the strings are empty. I also changed the comparison to use IsWhitespaceOrEmpty in case you have a bunch of spaces (which is generally not valid input). You could also use IsNullOrEmpty, which is generally considered better practice than == "".
Because you are dealing with text boxes (whose strings are never null) you would still be ok using the old comparison, however.
Upvotes: 1
Reputation: 125620
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)));
}
Upvotes: 0