Taken this is Windows Forms....
In the first example you don't examine if there is a selected index or not so it clearly fails when there is no selection.
If the second example fails with the same exact exception, then perhaps the problem is caused by the location of your code. If you execute the code too early the control may not yet be created. You can investigate the situation from
Control.IsHandleCreated Property (System.Windows.Forms)[
^]
For example if you call the following code from the form constructor you get the message that the listview isn't created yet. Also if you omit the message and let the code run, you can see that there are three items in the listview so deletion hasn't taken place.
If you call it for example from a button click event, it should work fine
public void RemoveItems(bool omitCheck=false) {
if (!omitCheck) {
if (!this.listView1.IsHandleCreated) {
MessageBox.Show("Listview not fully created yet");
return;
}
}
this.listView1.MultiSelect = true;
this.listView1.Items.Add("First");
this.listView1.Items.Add("Second");
this.listView1.Items.Add("Third");
foreach (ListViewItem item in this.listView1.SelectedItems) {
this.listView1.Items.Remove(item);
}
this.listView1.Items[0].Selected = true;
this.listView1.Items[2].Selected = true;
foreach (ListViewItem item in this.listView1.SelectedItems) {
this.listView1.Items.Remove(item);
}
}