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

筅森魡賤 提交于 2019-12-30 04:24:54

问题


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.


回答1:


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.




回答2:


For Each item In SuppliersCheckList.CheckedItems
        If SuppliersCheckList.GetItemCheckState(SuppliersCheckList.Items.IndexOf(item)) Then
            MsgBox(item.ToString)
        End If
Next


来源:https://stackoverflow.com/questions/2505119/for-each-item-in-checkedlistbox-item-returns-as-object-and-not-as-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!