views:

105

answers:

4

Hi,

I want to have a user control which will add some checkboxes in a asp.NET panel dynamically.

Simply I was believing I can do that easily in control's OnPreInit method. But the thing is I have learn that I cannot use and override OnPreInit method on Controls; it is only used for pages.

I do not want to solve this from the page by calling a method on the control.

So, if I cannot use PreInit on controls, where is the right place to add my checkboxes dynamically?

Do I miss something? Any advices?

thanks.

A: 

You can also do it in Page_Load event. Whats the problem in that?

Devi
ViewState of the controls are loaded in Init event. If I add the controls on Load event, in Init event the ViewState will be tried to get loaded while the controls are not existing. So it cannot work in that way.
burak ozdogan
For dynamic controls viewstate will be there in each postback but the controls will not be there, so you have to create those controls in each postback in Page_Load.
Devi
A: 

if your trying to use the values of the checkedboxes, try using

 Page.Form.FindControl("ID")
Madi D.
It is not about finding them but creating them at the right place actually.
burak ozdogan
A: 

Hello,

I think a lot really depends on what you want to do with them - you should be aware that controls added dynamically get their own lifecycle of sorts (googling should get you a ton of information, but essentially they will "catch up" on any phases they missed). I only mention this as you may want to look into some of the pitfalls - when I first went through it I spent a few days getting my head around it.

To answer your question I would suggest the best place will be to add the checkboxes during the OnInit phase of the control. For your information I have provided below the standard order that events occur during a standard page load with a normal custom control declared on the page.

Page: Constructor

Page: OnPreInit

---- Declared Controls Constructed ----

Control: OnInit

Page: OnInit

Page: OnInitComplete

Page: LoadViewState

Control: LoadViewState

Page: OnPreLoad

Page: OnLoad

Control: OnLoad

---- Any Control Events (e.g. btnClick) ----

Page: OnLoadComplete

Page: OnPreRender

Control: OnPreRender

Page: OnPreRenderComplete

Page: SaveViewState

Control: SaveViewState

Page: OnSaveStateComplete

Page: Render

Page: RenderChildren  -> Control: Render

Control: OnUnload

Page: OnUnload
Chris
A: 

The general rule of thumb is to create custom controls as soon as you possibly can. All of the events for controls will happen properly up until PreRender. If you add custom controls at PreRender they do not get their viewstate loaded or events called.

Earlz