Reputation: 483
How do I make an if statement that asks if multiple listBoxes are empty or not?
This is what I have so far...is it possible to combine it into one single if statement?
if (listBoxEmails.Items.Count < 1)
{
//Perform action
}
if (listBoxWebsites.Items.Count < 1)
{
//Perform action
}
if (listBoxComments.Items.Count < 1)
{
//Perform action
}
Upvotes: 1
Views: 88
Reputation: 17402
Is this in WPF or WinForms? You could do:
var performAction = (!listBoxEmails.Items.IsEmpty | !listBoxWebsites.Items.IsEmpty | !listBoxComments.Items.IsEmpty);
if (performAction)
{
}
Upvotes: 0
Reputation: 48686
If you are trying to get a count from ALL list boxes on your form, you can do this:
if (Controls.OfType<ListBox>().Any(z => z.Items.Count < 1))
{
// Do Something
}
The magic is that if you delete or add any more list boxes on your form, you won't have to change any code. If you want to grab specific listbox's, you could set the Tag
property on all the listbox's you want included to something like CountedListBox
and then do this:
if (Controls.OfType<ListBox>().Any(z => z.Items.Count < 1 && ((string)z.Tag == "CountedListBox")))
{
// Do something
}
Upvotes: 3
Reputation: 9739
You can have list boxes in some collection and using linq you can find in one statement if the any of the list is empty or not. Something like this. Of course there can be different approaches for list box collections.
private void ValidateListBoxes()
{
List<ListBox> listBoxes = new List<ListBox>();
listBoxes.Add(listBoxEmails);
listBoxes.Add(listBoxWebsites);
listBoxes.Add(listBoxComments);
bool isContainingEmptyList = listBoxes.Any(l => l.Items.Count < 1 || l.Items.Count==0);
}
Upvotes: 2
Reputation: 389
if (listBoxEmails.Items.Count >= 0 && listBoxWebsites.Items.Count >= 0 &&
listBoxComments.Items.Count >= 0)
{
//perform action
}
Upvotes: 1
Reputation: 7277
Here is the most simple solution I can think of,
if (listBoxEmails.Items.Any() && listBoxWebsites.Items.Any() && listBoxComments.Items.Any())
{
// Do something here,
}
Upvotes: 0