gpt4 book ai didi

winforms - 窗体 : Represent a single ListBox item in a foreach statement

转载 作者:行者123 更新时间:2023-12-02 00:38:36 24 4
gpt4 key购买 nike

如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com