E.T.
E.T.

Reputation: 367

How to do a loop on all unchecked items from checkedlistbox C#?

I was working on a method and then I realized that I had a foreach loop that ran through all checkedItems, instead of running through all unchecked item.

foreach ( object itemChecked in checkedListBox1.CheckedItems)
{(...)}

I was wondering if there is way to do this without changing the code too much. Regards

Upvotes: 6

Views: 7549

Answers (2)

mburakkalkan
mburakkalkan

Reputation: 1178

Cast the items as a CheckBox enumerable then you can loop:

foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
    if (!cb.Checked)
    {
        // your logic
    }
}

Upvotes: 0

OhBeWise
OhBeWise

Reputation: 5454

Two options:

  1. Loop through all Items and check them against the CheckedItems.
  2. Use LINQ.

Option 1

foreach (object item in checkedListBox1.Items)
{
  if (!checkedListBox1.CheckedItems.Contains(item))
  {
    // your code
  }
}

Option 2

IEnumerable<object> notChecked = (from object item in checkedListBox1.Items
                                  where !checkedListBox1.CheckedItems.Contains(item)
                                  select item);

foreach (object item in notChecked)
{
  // your code
}

Upvotes: 11

Related Questions