ChristianLinnell
ChristianLinnell

Reputation: 1398

Casting a ListBox.SelectedObjectCollection to a ListBox.ObjectCollection?

Is it possible to cast a ListBox.SelectedObjectCollection to a ListBox.ObjectCollection in C#? If so, how would I go about it?

Upvotes: 2

Views: 10318

Answers (5)

Ram
Ram

Reputation: 3

This is my answer I used to convert Checked list box to list box

CheckedListBox.CheckedItemCollection s= checkedListBox1.CheckedItems;

        List<object> ns = new List<object>();

        foreach (object ob in s)
        {
            ns.Add(ob);
        }

        listBox1.Items.AddRange(ns.ToArray());

Upvotes: 0

Harsha
Harsha

Reputation: 1879

Here is my answer: it is working for me.

System.Windows.Forms.ListBox.SelectedObjectCollection lst  =this.lstImage.SelectedItems;
List<string> selectedItems = new List<string>();

foreach (object obj in lst)
{
    selectedItems.Add(obj.ToString());
}

Upvotes: 1

jhoanna
jhoanna

Reputation: 1857

I have a function that accepts List<string>.

I can pass both SelectedItems and Items by casting them.

Try this:

SelectedItems.Cast<string>().ToList()
Items.Cast<string>().ToList()

<string> could be replaced with some other object type.

Upvotes: 11

Muhammad Mubashir
Muhammad Mubashir

Reputation: 1657

  List<YourDataType> YourDataTypeList = new List<YourDataType>();
  for (int i = 0; i < lbVectors.SelectedItems.Count; i++)
   {
        YourDataType v = lbVectors.SelectedItems[i] as YourDataType;
        YourDataTypeList .Add(v);
    }  

Upvotes: 0

SLaks
SLaks

Reputation: 888087

This is not possible.

Instead, you should use an IList.
Both of these types implement IList, so you can pass either one as an IList without any explicit casting.

If you really wanted to, you could create a new ListBox.ObjectCollection and add the items from the SelectedObjectCollection.

Upvotes: 4

Related Questions