作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 foreach 语句中重复列表框中的单个项目?
我已经尝试过 ListBoxItem,但 System.Windows.Controls 在我的 .Net 框架(版本 4)中不被视为有效的命名空间。
foreach(ListBoxItem item in listBoxObject.Items)
{
...
}
最佳答案
通常,当有人循环浏览列表框项目时,他们希望确定它们是否被选中。如果是这种情况,请尝试使用 listBoxObject.SelectedItems 而不是 listBoxObject.Items。这将仅返回已选择的项目。
据我所知,没有 ListBoxItem 对象。您将需要为每个项目使用对象(这是 seletecteditems 和 items 返回的内容)。 Object 表示项目的值,因此请相应地使用它(意思是,如果对象是字符串,则将其用作字符串,但如果对象是复杂对象,则按原样使用)。
代码示例:
foreach (Object listBoxItem in listBoxObject.SelectedItems)
{
//Use as object or cast to a more specific type of object.
}
如果您知道什么对象将始终是您可以将其转换为 foreach 循环。 (警告:如果你错了,这将引发异常)。这个例子是如果只有字符串被输入到列表框中。
foreach (String listBoxItem in listBoxObject.SelectedItems)
{
//Use as String. It has already been cast.
}
关于winforms - 窗体 : Represent a single ListBox item in a foreach statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3575322/
我是一名优秀的程序员,十分优秀!