Collection

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
 
H

Herfried K. Wagner [MVP]

* 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top