checking whether a CheckedListBox is empty
I have a small form in which the user writes the name of some item, and then when he clicks "Add" there is a statement that needs to check if there is already the same item in the checkedListBox.
I'm looking for the "if" statment that checked if the list is empty or with some 开发者_开发百科item.
private void button2_Click(object sender, EventArgs e)
{
foreach (var item in checkedListBox1.Items)
{
if (itemName.Text == item.ToString())
{
DialogResult result = MessageBox.Show("?", "Question", MessageBoxButtons.YesNoCancel);
if (result == DialogResult.Yes)
{
checkedListBox1.Items.Add(itemName.Text);
}
else if (result == DialogResult.No)
{
//clear the forms
}
}
else
{
checkedListBox1.Items.Add(itemName.Text);
timeLeft = 2;
timer1.Start();
}
}
}
//checkedListBox1.Items.Add(itemName.Text);
//timeLeft = 2;
//timer1.Start();
if(checkedListBox1.Items.Count > 0) {
// It contains items
} else {
// It doesn't
}
EDIT: is for checking if the CheckedListBox is empty or not, then
if(checkedListBox1.Items.Contains(theItemToCheck)) {
// The item is already in the CheckedListBox
}
is to check if an item is already in the CheckedListBox.
You can check if your ListBox
contains the item just by using the Contains method of the collection:
if (checkListBox1.Items.Contains(itemName.text))
{
//do something
}
Well, your code will not work since you may not modify the collection you are iterating.
Trying to do so will result in an InvalidOperationException
(Collection was modified; enumeration operation may not execute.)
You should terminate the loop when you find your match, then get user confirmation and after that modify the list/collection.
So:
- Try to find a match (and break out of the loop if you are looping over the collection)
- Get user confirmation
- Modify the collection
Can you get a look at LINQ?
var exists = checkedListBox1.Items.Where(item => item == itemName.Text).Any();
if(exists)
item exists
else
item doesn't exists
There should be something like checkedListBox1.Items.Count .
Try:
if(checkedListBox.Items.Count()>0)
{
// it means you have items
}
else
{
// it means you have empty checkedListBox
}
精彩评论