【发布时间】:2017-06-21 10:59:45
【问题描述】:
我有一个用户填充条目的列表框。我正在尝试遍历列表框并获取每个条目的 SelectedIndex 和 Value,但出现错误:
无法将“System.String”类型的对象转换为类型 'System.Windows.Forms.ListBox'
我在表单上的列表框称为 listEvents。
这是我所拥有的:
foreach (ListBox item in listEvents.Items)
{
string eventName = item.Text;
int index = item.SelectedIndex;
//do some stuff with these variables
}
我尝试使用 ListViewItem 代替 Listbox,但这也不起作用(我必须将 item.SelectedIndex 更改为 item.Index,并且 listEvents 列表框控件没有 Index 属性,只有 SelectedIndex) .
感谢任何帮助。
【问题讨论】:
-
您会收到该错误,因为您正在寻找每个
item的数据类型为ListBox的listEvents.Items中的listEvents.Items,我假设它包含字符串。参考下面@Graffito 的回答。 -
ListBox有一个SelectedIndex- 项目没有。您是指每个项目的 index 吗?