listBox.Items.Remove help

  • Thread starter Thread starter Bilo
  • Start date Start date
B

Bilo

I dont know what i am doing false.
the code :

private void button2_Click(object sender, System.EventArgs e)
{
foreach (string filename in listBox1.SelectedItems)
listBox1.Items.Remove(filename);
}
gives me the error :

System.InvalidOperationException: The list that this enumerator is bound to
has been modified. An enumerator can only be used if the list doesn't
change.
at
System.Windows.Forms.EntryEnumerator.System.Collections.IEnumerator.MoveNext
()

Anyone can help?
 
Hello Bilo,
I dont know what i am doing false.
the code :
private void button2_Click(object sender, System.EventArgs e)
{
foreach (string filename in listBox1.SelectedItems)
listBox1.Items.Remove(filename);
}
gives me the error :

System.InvalidOperationException: The list that this enumerator is
bound to
has been modified. An enumerator can only be used if the list doesn't
change.
at
System.Windows.Forms.EntryEnumerator.System.Collections.IEnumerator.Mo
veNext
()

You can't modify a collection if you are iterating it with an Enumerator.

It appears to me that this line may suffice for what you're trying to accomplish.

listBox1.Items.Clear();
 
Had also asked at dotnet.language.csharp .
Get the answer:
The problem is when it removes a item than listBox1.SelectedItems is
changed. But it must be constant till end of foreach.
So i must first copy the selected items into an arry. and make the foreach
with the copy.
 
Back
Top