4

I have a ListBox which supports Multi-Select and I need a way to retrieve all the selected indexes as a List<int>.

for example:

Listbox
{
    item 1 - not selected
    item 2 - selected
    item 3 - selected
    item 4 - not selected
}

So the selected indexes List<int> will look like:

List<int>() { 1, 2 };
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
David Shnayder
  • 333
  • 4
  • 14

1 Answers1

4

Try this:

List<int> list = new List<int>();

foreach (var item in listBox1.SelectedItems)
{
   list.Add(listBox1.Items.IndexOf(item));// Add selected indexes to the List<int>
}

Or with linq:

List<int> list = (from object obj in listBox1.SelectedItems 
                  select listBox1.Items.IndexOf(obj)).ToList();
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • What if two of the selected items are equal? Won't `IndexOf()` then return the first one's index twice? – Malcolm Mar 20 '19 at 20:25
  • If the the selection contains duplicate elements, you'll need to do something like [this](https://stackoverflow.com/a/6509810/1168116) instead. – Malcolm Mar 20 '19 at 20:37