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

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

问题描述

我有一个CheckedListBox以前填充。我想通过CheckedListBox中的所有项目循环使用for each / next,并对checkedlistbox的每个迭代元素执行大量填充操作。



示例代码:

 对于CheckedListBox1.Items中的每个项目

如果item.Checked = True然后

'做类似
的东西item.BackColor = Color.Blue

else

'做其他的东西
item.BackColor = Color.Brown

End If

Next

问题在于对象类型,而不是控制类型。如果我强制迭代变量为复选框,它会抛出一个InvalidCastException,说该类型System.String不能与类型System.Windows.Forms.CheckBox关联

<我知道我可以很容易地解决这个问题,但是我想为每个/下一个循环使用一个循环,因为我在这个循环中有很多代码(并且不能使用),并且总是直接对象希望避免,我真的需要代码尽可能简单。



我实际上花了一个下午寻找这个,但无法找到任何答案。 >

解决方案 CheckedListBox 不是 CheckBox 控件。

它没有包装对象的集合。

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

您应该使用 ListView (将code> CheckBoxes 属性设置为true)。
然后你可以遍历 ListViewItem code> Items 集合中的code>实例。

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.

解决方案

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.

这篇关于对于每个&lt;项目&gt;在CheckedListBox中。 &LT;项目&GT;返回对象而不是控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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