vb.net 对于 CheckedListBox 中的每个 <item>。<item> 返回为 Object 而不是 Control
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2505119/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
For each <item> in CheckedListBox. <item> returns as Object and not as Control
提问by Tivie
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.
我以前填充了一个 CheckedListBox。我想在 CheckedListBox 中的所有项目中使用“for each / next”循环,并对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'
问题是它是“对象”类型而不是“控制”类型。如果我强制迭代 var As CheckBox,它会抛出一个 InvalidCastException,说明类型“System.String”不能与类型“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.
我知道我可以轻松解决这个问题,但我想为每个 /next 循环使用 a,因为我在该循环中有很多代码(并且不能使用 With)并且总是直接指向对象是我希望的避免,我真的需要代码尽可能简单。
I actually spent one afternoon looking for this but couldn't find any answer.
我实际上花了一个下午来寻找这个,但找不到任何答案。
采纳答案by SLaks
A CheckedListBox
is not a collection of CheckBox
controls.
It does not have a collection of wrapper objects.
ACheckedListBox
不是CheckBox
控件的集合。
它没有包装器对象的集合。
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)
CheckedListBox 控件是一个简单的控件,它只能显示一个简单的项目列表;听起来你正在寻找更强大的东西。(例如,没有所有者绘图是不可能更改单个项目的背景颜色的)
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.
您应该改用 a ListView
(CheckBoxes
属性设置为 true)。
然后,您可以遍历ListViewItem
其Items
集合中的实例。
回答by I Lavi
For Each item In SuppliersCheckList.CheckedItems
If SuppliersCheckList.GetItemCheckState(SuppliersCheckList.Items.IndexOf(item)) Then
MsgBox(item.ToString)
End If
Next