对于每个- 在检查列表框中。<项目>作为对象返回,而不是作为控件返回项目>
我之前填充了一个 CheckedListBox。我想使用“for every / next”循环遍历 CheckedListBox 中的所有项目,并对 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”关联
我知道我可以轻松解决这个问题,但我想使用a for every /next 循环,因为我在该循环中有很多代码(并且不能使用 With)并且总是直接指向对象是我希望避免的事情,我真的需要代码尽可能简单。
我实际上花了一下午的时间寻找这个但找不到任何答案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CheckedListBox
不是CheckBox
控件的集合。它没有包装对象的集合。
CheckedListBox 控件是一个简单的控件,只能显示简单的项目列表;听起来你正在寻找更强大的东西。 (例如,如果没有所有者绘制,就不可能更改单个项目的背景颜色)
您应该使用
ListView
(将CheckBoxes
属性设置为 true) .然后,您可以循环访问其
Items
集合中的ListViewItem
实例。A
CheckedListBox
is not a collection ofCheckBox
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 theCheckBoxes
property set to true) instead.You can then loop through the
ListViewItem
instances in itsItems
collection.