【问题标题】:Need help looping through contents of a ListBox需要帮助遍历 ListBox 的内容
【发布时间】: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 的数据类型为ListBoxlistEvents.Items 中的listEvents.Items,我假设它包含字符串。参考下面@Graffito 的回答。
  • ListBox 有一个SelectedIndex - 项目没有。您是指每个项目的 index 吗?

标签: c# listbox


【解决方案1】:
int index = listEvents.SelectedIndex;
foreach (object item in listEvents.Items){
    string eventName = (string)item;
    // ...
}

【讨论】:

  • 对象是否具有SelectedIndex 属性?
  • 它没有。在此示例中,我将如何获取索引?或者我应该只增加一个 int 变量来表示索引(假设它从 0 向前顺序循环)?
  • @reptiletim & FarzinKanzi:当然不是,我更新了我的答案。
  • 我认为它只会在循环运行时返回表单上当前选定的索引。因此SelectedIndex 将返回不正确的值。
【解决方案2】:

如果您想要每个项目的索引,只需使用 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.
   ...
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 为什么选演员?还有ToList?和ForEach?这段代码是不必要的混乱。
    【解决方案4】:

    没有方法可以指定一个项目的索引,但是你可以得到它的值。

    foreach (ListItem item in listEvents.Items)
            {
                string eventName = item.Text;
                string value = item.Value;
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-30
      • 2021-12-18
      • 1970-01-01
      相关资源
      最近更新 更多