For each <item> in CheckedListBox. <item> returns as Object and not as Control
Posted
by Tivie
on Stack Overflow
See other posts from Stack Overflow
or by Tivie
Published on 2010-03-24T03:18:34Z
Indexed on
2010/03/24
3:23 UTC
Read the original article
Hit count: 316
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
© Stack Overflow or respective owner