For each <item> in CheckedListBox. <item> returns as Object and not as Control

Tivie picture Tivie · Mar 24, 2010 · Viewed 26.7k times · Source

I have a CheckedListBox previously populated. I want to loop with a "for each / next" through all items in the CheckedListBox and do a lot of "stuff" with each iteration element of the checkedlistbox.

example code:

    For Each item In CheckedListBox1.Items

        If item.Checked = True Then

            'do stuff like
            item.BackColor = Color.Blue

        Else

            'do other stuff
            item.BackColor = Color.Brown

        End If

    Next

the problem is that is an 'Object' type and not a 'Control' type. If I force the iteration var As CheckBox, it throws an InvalidCastException saying that type 'System.String' can't be associated with type 'System.Windows.Forms.CheckBox'

I know I can easily work around this but I want to use a for each /next loop since I have a lot of code in that loop (and With can't be used) and always poiting directly to the object is something I wish to avoid and I really need the code to be as simple as possible.

I actually spent one afternoon looking for this but couldn't find any answer.

Answer

SLaks picture SLaks · Mar 24, 2010

A CheckedListBox is not a collection of CheckBox controls.
It does not have a collection of wrapper objects.

The CheckedListBox control is a simple control that can only display a plain list of items; it sounds like you're looking for something more powerful. (For example, it is impossible to change the background color of an individual item without owner-drawing)

You should use a ListView (with the CheckBoxes property set to true) instead.
You can then loop through the ListViewItem instances in its Items collection.