对于每个<item>在 CheckedListBox 中.<项目>返回为对象而不是控件 [英] For each <item> in CheckedListBox. <item> returns as Object and not as Control

查看:17
本文介绍了对于每个<item>在 CheckedListBox 中.<项目>返回为对象而不是控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前填充了一个 CheckedListBox.我想在 CheckedListBox 中的所有项目中使用for each/next"循环,并对checkedlistbox的每个迭代元素做很多东西".

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.

示例代码:

    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

问题在于它是对象"类型而不是控制"类型.如果我强制迭代 var As CheckBox,它会抛出一个 InvalidCastException,说明类型System.String"不能与类型System.Windows.Forms.CheckBox"相关联

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'

我知道我可以轻松解决这个问题,但我想为每个/next 循环使用 a,因为我在该循环中有很多代码(并且 With 不能使用)并且总是直接指向对象是什么我希望避免,我真的需要代码尽可能简单.

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.

推荐答案

CheckedListBox 不是 CheckBox 控件的集合.
它没有包装对象的集合.

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

CheckedListBox 控件是一个简单的控件,只能显示一个普通的项目列表;听起来你正在寻找更强大的东西.(例如,没有所有者绘图是不可能改变单个项目的背景颜色的)

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)

您应该改用 ListView(将 CheckBoxes 属性设置为 true).
然后,您可以循环遍历其 Items 集合中的 ListViewItem 实例.

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.

这篇关于对于每个<item>在 CheckedListBox 中.<项目>返回为对象而不是控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆