Removing a child control in event it fires

G

Guest

Hi,

I was wondering if it's possible to remove a Control c from a Controls
collection in the parent's event handler for an event fired by c.

For instance let's say we have

public class ChildControl : Control
{
public event EventHandler WorkDone(object sender, EventArgs e);
}

public class ParentControl : Control
{
protected override void OnLoad(EventArgs e)
{
ChildControl c = new ChildControl();
c.WorkDone += new EventHandler(ChildWorkDone);
this.Controls.Add(c);
}

private void ChildWorkDone(object sender, EventArgs e)
{
this.Controls.Remove(c);
}
}


Whenever I try something like this, I get an HttpException ("A control
cannot modify its parents' control collections"). True, the child itself
fired the event, but it's not modifying the collection - the parent is.

What is the preferred method to accomplish what I'm trying to do? I suppose
I could always set a boolean or something during the event handler, then
remove the control at a later stage in the pipeline (like PreRender) but that
seems "hackish" to me. I have this same thing happening in another app but
it works fine...

Thanks for any suggestions.
 
J

Joel Martinez

I could swear that I've done this before and it worked ... eh, don't
bother with a flag, just have an ArrayList called something like
ToRemove. When the event fires, add the sender to the ToRemove array.
Then, in PreRender, just iterate through the collection and remove
anything that is in there.

Hope that helps,
Joel Martinez
http://www.onetug.org - Orlando .NET User Group
http://www.codecube.net - blog
 

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