C# 需要帮助循环浏览列表框的内容吗

C# 需要帮助循环浏览列表框的内容吗,c#,listbox,C#,Listbox,我有一个列表框,用户用条目填充它。我试图遍历列表框并获取每个条目的SelectedIndex和值,但我得到一个错误: 无法将“System.String”类型的对象强制转换为 'System.Windows.Forms.ListBox' 表单上的列表框称为listEvents 以下是我所拥有的: foreach (ListBox item in listEvents.Items) { string eventName = i

我有一个列表框,用户用条目填充它。我试图遍历列表框并获取每个条目的SelectedIndex和值,但我得到一个错误:

无法将“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 Listbox控件没有Index属性,只有SelectedIndex)


感谢您的帮助

没有方法指定项的索引,但您可以获取该项的值

int index = listEvents.SelectedIndex;
foreach (object item in listEvents.Items){
    string eventName = (string)item;
    // ...
}
foreach (ListItem item in listEvents.Items)
        {
            string eventName = item.Text;
            string value = item.Value;
        }

或者试试这个。乱七八糟的代码,但得到了所需的索引

listEvents.Items.Cast<object>().ToList().ForEach(li => {
    int i = 0;
    string eventName = li.ToString();
    int index = 0;
    i++;
});
listEvents.Items.Cast().ToList().ForEach(li=>{
int i=0;
字符串eventName=li.ToString();
int指数=0;
i++;
});

如果您想要每个项目的索引,只需使用
for
循环:

for(int i = 0; i < listEvents.Items.Count; i++)
{
   string value = listEvents.Items[i].ToString();
   // or object value = listEvents.Items[i]; if the listbox is bound to a collection of objects.
   ...
}
for(int i=0;i
对象是否具有
SelectedIndex
属性?它没有。在本例中,如何获取索引?或者我应该只增加一个int变量来表示索引(假设它从0开始按顺序循环)?@Ravidetim&FarzinKanzi:当然不是,我更新了我的答案。我认为它只会在循环运行时返回表单上当前选定的索引。因此,
SelectedIndex
将返回不正确的值。之所以会出现此错误,是因为您在
listEvents.Items
中查找数据类型为
ListBox
的每个
项,我假定它包含字符串。请参阅下面@Graffito的答案。
列表框中有一个
SelectedIndex
-这些项目没有。你是说每个项目的索引吗?为什么是演员阵容?和
列表
?和ForEach
?这段代码是不必要的混乱。