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)
            {
            //...
            }
                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) {
    // ..
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With