Question

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!

Was it helpful?

Solution

Only Dispose an object after everything is completely done with it. Trying to do anything with the object after it is disposed will result in undefined behavior. Think of it as freeing the memory.

Fortunately, Windows forms disposes these objects for you when you close the form. The only case you would need to dispose them in your code is if you remove the objects from the form.

Take a look at the .Designer.cs file, and you will see the form's Dispose() method:

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }
    base.Dispose(disposing);
}

The components.Dispose() will recursively clean up all the components on the form, including those in the panel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top