Start counting from end to zero
for (int i = listView1.Items.Count - 1; i >= 0; i--) { if (listView1.Items[i].Selected) { listView1.Items[i].Remove(); } }
However, keep in mind that each ListViewItem has an Index property, and using this collection has the advantage of avoiding redundant test and cyclic switching to fewer elements.
(Note: the collection of SelectedItems is never null, if there is no selection, the collection is empty but not null)
So your code can 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", ...);
Steve source share