Initializing Controls in CreateChildControls

Once again in my adventure of writing custom controls I have discovered that if you are overwriting custom CreateChildControls to add your own controls to the control collection, you should initialize the controls before adding them to the control collection.  Here is an example where I am setting properties on the link button after I add them to the controls collection. 

image

The reason this is not a good approach is because of the magic that happens when you call controls.Add. This is a phase when .net framework calls an internal method called StartTrackingViewState. Basically once the control is added to the control collection, it gets tracked.  Anything that you do to the control after adding it to the control collection gets recorded in the viewstate causing the page size to increase. Since childcontrols gets called every time the control needs to get initialized, the initialization code for the control will execute every time and therefore there is no need to have anything being persisted to the viewstate. So as good practice always initialize your controls before adding them to the controls collection as follows.

 

image

1 Comment

Comments have been disabled for this content.