Delete Items from ListView in C#
Start counting from the end going to zero
for (int i = listView1.Items.Count - 1; i >= 0; i--)
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
}
}
However consider that every ListViewItem has an Index property and using that collection has the advantage to avoid a redundant test and looping on a lesser number of items.
(Note, the SelectedItems collection is never null, if no selection is present, then the collection is empty but not null)
So your code could be rewritten
if (listView1.SelectedItems.Count > 0)
{
var confirmation = MessageBox.Show("Voulez vous vraiment supprimer les stagiaires séléctionnés?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirmation == DialogResult.Yes)
{
for (int i = listView1.SelectedItems.Count - 1; i >= 0; i--)
{
ListViewItem itm = listView1.SelectedItems[i];
listView1.Items[itm.Index].Remove();
}
}
}
else
MessageBox.Show("aucin stagiaire selectionnes", ...);
You should not reference the original collection you are using during iteration, but some other:
foreach(ListViewItem item in listView1.Items)
if (item.Selected)
listView1.Items.Remove(item);