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

2

6

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

Gladiolus answered 14/5, 2015 at 14:53 Comment(0)
L
11

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
}
Lesko answered 15/5, 2015 at 16:58 Comment(0)
G
0

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

foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
    if (!cb.Checked)
    {
        // your logic
    }
}
Glorianna answered 1/6, 2016 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.