Disposing Dynamic Controls
Posted on 2010-09-09
I started running the code analysis tool in Visual Studio 2010 to try to improve my code. One thing it's complaining about is that I'm not dispossing of some objects (specifically dynamically created controls). For example,
dim control as new Label()
The code analyzer complains that not all code paths dispose control. I tried changing my code to this
using control as new Label()
This satified the code analyzer complaint. However, this seems wrong to me. Shouldn't the control continue to exist in the containerControl.Controls list and wouldn't trying to dispose of it before page processing is done cause problems? However, from my testing everything still seems to work fine.
I suppose another approach would be to store all dynamically created controls in an array and dispose of them in Unload().
Does anyone have any advice for this?