【问题标题】:Cannot convert SelectedObjectCollection to ObjectCollection ?无法将 SelectedObjectCollection 转换为 ObjectCollection ?
【发布时间】:2011-12-04 03:49:22
【问题描述】:

如果没有选择或选择一个项目,我试图从 ListBox 中获取所有元素的列表,或者如果选择了超过 1 个,我正在尝试从 ListBox 中获取所有元素的列表。我已经写了这样的代码,但它没有编译:

    ListBox.ObjectCollection listBoXElemetsCollection;

    //loading of all/selected XMLs to the XPathDocList
    if (listBoxXmlFilesReference.SelectedIndices.Count < 2)
    {
        listBoXElemetsCollection = new ListBox.ObjectCollection(listBoxXmlFilesReference);
    }
    else
    {
        listBoXElemetsCollection = new ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
    }

因此,要使这段代码正常工作,我需要使用类似 ListBox.SelectedObjectCollection listBoxSelectedElementsCollection; 的东西,这是我不想要的,因为我想在这样的 foreach 中使用它:

            foreach (string fileName in listBoXElemetsCollection)
            {
            //...
            }

【问题讨论】:

标签: c# winforms listbox


【解决方案1】:

如果你不需要的话,我会简单地做一点,不要弄乱 ListBox ObjectCollections。既然您想将 ListBox 上的项目作为字符串进行迭代,为什么不使用 List 并加载列表的显示方式:

List<string> listItems;

if (listBoxXmlFilesReference.SelectedIndices.Count < 2) {
    listItems = listBoxXmlFilesReference.Items.Cast<string>().ToList();
} else {
    listItems = listBoxXmlFilesReference.SelectedItems.Cast<string>().ToList();
}

foreach (string filename in listItems) {
    // ..
}

【讨论】:

    【解决方案2】:

    您需要将SelectedObjectCollection 转换为object[] 的数组。

    ListBox.SelectedObjectCollection sel = new 
                         ListBox.SelectedObjectCollection(listBoxXmlFilesReference);
    ListBox.ObjectCollection col = new 
                         ListBox.ObjectCollection(listBoxXmlFilesReference,
                             sel.OfType<object>().ToArray());
    

    【讨论】:

      【解决方案3】:

      我可以看到您要执行的操作,但它无法编译,因为 ListBox.ObjectCollection 类型与 ListBox.SelectedObjectCollection 不同 - 即使在您的情况下它们是包含字符串的列表,类本身也不同,因此编译错误。

      假设您的项目是列表框中的字符串,您可以这样做:

      var items = listBoXElemetsCollection.Items.OfType<string>();
      if (listBoXElemetsCollection .SelectedIndices.Count >= 2)
            items = listBoXElemetsCollection.SelectedItems.OfType<string>();      
      
      foreach(var item in items)
                  //do stuff
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-29
        • 2015-09-04
        • 2016-05-26
        • 2015-08-11
        相关资源
        最近更新 更多