For each in CheckedListBox. returns

2019-02-09 06:28发布

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.

2条回答
家丑人穷心不美
2楼-- · 2019-02-09 06:43
For Each item In SuppliersCheckList.CheckedItems
        If SuppliersCheckList.GetItemCheckState(SuppliersCheckList.Items.IndexOf(item)) Then
            MsgBox(item.ToString)
        End If
Next
查看更多
可以哭但决不认输i
3楼-- · 2019-02-09 06:49

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.

查看更多
登录 后发表回答