Collection

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi again

I've been trying to erase an element from a Collection,
but when I do this I get this exception

Object reference not set to an instance of an object.

This is my code

IEnumerator ie = Panel.Controls.GetEnumerator();
while(ie.MoveNext()) {
CheckBox chk = new CheckBox();
chk = (CheckBox)ie.Current;

if(chk.checked) {
Panel.Controls.Remove(chk);
}
}

And when I comment the condition, it removes only some
elements, for example, if the panel has 27 elements, it
removes 10 and it leaves 17.

What's wrong??

Regards
 
* said:
I've been trying to erase an element from a Collection,
but when I do this I get this exception

Object reference not set to an instance of an object.

This is my code

IEnumerator ie = Panel.Controls.GetEnumerator();
while(ie.MoveNext()) {
CheckBox chk = new CheckBox();
chk = (CheckBox)ie.Current;

if(chk.checked) {
Panel.Controls.Remove(chk);
}
}

And when I comment the condition, it removes only some
elements, for example, if the panel has 27 elements, it
removes 10 and it leaves 17.

Don't remove the controls when looping through the collection. Instead
you can collect the controls which should be removed and remove all of
them after finishing the loop.
 
Back
Top