views:

635

answers:

1

Hello there.

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 using

for i=0 to CheckedListBox.Items.Count - 1

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.

If someone could be kind enough to enlight me in this, it would be extremely appreciated.

Best regards

+1  A: 

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.

SLaks
Thanks for your quick reply.I guess I could, but using a Listview seems kind of an overshot for something as simple as a list of checkedboxes with some text after.Besides working with the ListView class is a bit more difficult than with listboxes.I run a class of basic programming for Med Students and the whole point was showing how easy is to work with "For Each/Next" =D
Tivie
Yes, but CheckedListBox isn't powerful enough for you.
SLaks
Yeah, I ended up using ListView.I will leave the question open just in case someone figures it out ^^
Tivie
Not much to figure out, actually. The object you are getting is the actual object you added to the list (in your case, a string I believe). Not the "list item" created for it. Visually customizing the individual items would require coding an owner-drawn listbox, which would be another lesson altogether.
Ishmaeel