How to loop for all unverified items from checklistbox c #?

I worked on a method, and then realized that I have a foreach loop that ran through all the test items, rather than run through all the unverified items.

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

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

+4
source share
2 answers

Two options:

  • Skip all Itemsand check them out CheckedItems.
  • 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
}
+8
source

List the items as enumerated CheckBox items, then you can loop through:

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

All Articles