The three ImageButtons below are added to a panel (pBreakfast) in a page's codebehind:
ImageButton ibSR = new ImageButton();
ibSR.ID = "ibStickyRoll";
ibSR.ImageUrl = "/images/Breakfast.gif";
ibSR.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibSR);
ImageButton ibD = new ImageButton();
ibD.ID = "ibDoughnut";
ibD.ImageUrl = "/images/Breakfast.gif";
ibD.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibD);
ibD.Dispose();
using(ImageButton ibC = new ImageButton()){
ibC.ID = "ibCrepe";
ibC.ImageUrl = "/images/Breakfast.gif";
ibC.Click += new ImageClickEventHandler(ImageButton_Click);
pBreakfast.Controls.Add(ibC);
}
I expected either all three would work, or perhaps the disposed ImageButtons would generate an error or simply not appear. But what's happening is all three appear and don't cause any errors, but the event handler never fires for the ImageButtons that are disposed.
Why does disposing cause only the eventhandler hookup to go away?
I am dynamically adding TableRow's and TableCell's to a table on this same page and placing ImageButtons in one cell of each row. I am using 'using' with the TableRow's and TableCell's without any problem. There doesn't seem to be an issue with the outer (TableRow & TableCell) objects getting disposed; as long as I don't ever dispose of the dynamic ImageButtons, the eventhandler gets fired OK on click.
Is it OK, in this instance, to not ever dispose of the ImageButtons? I have taken StackOverflow's advice to heart and try to use using() on all my disposable objects -- so this is really bugging me.
Thanks!