Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 779
E.T. Avatar asked May 14 '15 14:05

E.T.


2 Answers

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
}
like image 155
OhBeWise Avatar answered Nov 14 '22 11:11

OhBeWise


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

foreach (CheckBox cb in checkedListBox1.Items.Cast<CheckBox>())
{
    if (!cb.Checked)
    {
        // your logic
    }
}
like image 32
Mustafa Burak Kalkan Avatar answered Nov 14 '22 09:11

Mustafa Burak Kalkan