Expanding a little in Rudolf's idea, using a List<T>
:
List<int> selected = new List<int>();
You can keep track of the items so far selected:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// add new selection:
foreach (int index in listBox1.SelectedIndices)
if (!selected.Contains(index)) selected.Add(index);
// remove unselected items:
for (int i = selected.Count - 1; i >= 0; i-- )
if (!listBox1.SelectedIndices.Contains(selected[i])) selected.Remove(i);
}
To test you can write:
for (int i = 0; i < selected.Count; i++)
Console.WriteLine("Item # " selected[i] + ": " + listBox1.Items[selected[i]]);
Note that when you use the expanded multiselection option you will get the usual, slightly weird Windows selection order..