views:

40

answers:

2

Where is the best place to create dynamic controls in ASP.NET? MSDN says Pre_init , another MSDN article says Init, and some people say the Load event (which I read isn't good to do).

I'm studying for a MS certification and I want to make sure I know which one is ideal and why. My initial thought would be to create the object in pre_init and assign any property values in the Load event (so that ViewState would be loaded for the dynamic control).

+1  A: 

I recommend Page_Init(). This will bypass the issue of ViewState not loading consistently. Controls will be accessible, but viewstate not yet applied to them. This is exactly where you want to add controls per the second article.

Also, based on experience, this is what works. any other approach else has caused me issues.

David Stratton
+1  A: 

It depends but I think the general consensus is the earlier the better. So if you are adding dynamic controls to a Page add them in the Pre_Init phase if you can. If you are adding custom controls to a user control add them in the Init phase if you can (controls don't have a Pre_Init).

There are situations where you can't add them that early.

  1. Adding a control in response to some user input (e.g. button click).
  2. You need to load a specific control based on the state of the page you are on. In this case you'll probably have to wait until the load event of the containing control to determine if you need to load the control or not.

As a general rule of thumb add them as soon as you can.

Dustin Hodges