Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert SelectedObjectCollection to ObjectCollection ?

I am trying to get a list of all elements from ListBox if no or one of items is selected or list of selected items if more than 1 are selected. I have written such a code but it doesn't compile :

    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);
    }

So for this piece of code to work I would need to use something like ListBox.SelectedObjectCollection listBoxSelectedElementsCollection; which I do not want because I would like to use it in such an foreach:

            foreach (string fileName in listBoXElemetsCollection)
            {
            //...
            }
like image 492
Patryk Avatar asked Jan 19 '23 03:01

Patryk


1 Answers

I'd simply this a bit and not mess with the ListBox ObjectCollections if you don't need to. Since you want to iterate items on your ListBox as strings, why not use a List and load the list how you show:

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) {
    // ..
}
like image 102
Jay Riggs Avatar answered Jan 22 '23 14:01

Jay Riggs