I just have a few questions about programmatically adding controls in aspx. After doing some research I just want to be sure I understand this correctly.
When you try to add controls programmatically you’re supposed to do this in a certain phase of the page life cycle.
-
Is the latest you can programmatically create and add controls is in the
page_load? -
Is it the best practice to create the controls in the
initialization phaseand is it because this is before theview stategets loaded? -
Do you have to keep re-creating the controls upon each
post back? Or is there a way to create it once and have it be persistent? -
If you change any controls in the
onInitphase that exists in theview statewill it be replaced automatically when theview stategets loaded? -
Does
ContentTemplateContainer.Controls.Add(...)add child controls? For example if you try to add a table that is filled with gridviews filled with buttons will there be apartial post backwhen one of those buttons is clicked? If not how are you supposed to add child controls to theUpdatePanel?
That is all the questions I can think up for now. Any clarification you guys can give me would be great!
Assuming you’re talking about webforms, and not mvc, you can add new dynamic controls at any phase of the lifecycle. However, it’s important to remember that every time you have a postback (including any server-side event) you are working with a different instance of your page than the one to which you first added your dynamic controls, because you are now preparing a response for a different http request. Once you understand that clearly, everything else starts to make a lot more sense.
So you want to add a control to the page in response to a button click. You can safely do that in the button’s click event, which is very late in the page life cycle. But now the user does something to trigger another post back. At this point, you are working with a different instance of the page class than you had before. You must add the dynamic control to the page again if you want it to still be on the page after the postback completes. If you also want to use the ViewState for this control, you must do this before (not during) the Page_Load event. The most common place to do this is in Page_Init.
I think that covers most of your points.