Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET - Dynamic controls created in Page_Pre_init() or Page_Init() or Page_Load()

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).

like image 233
contactmatt Avatar asked Oct 25 '10 18:10

contactmatt


2 Answers

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.

like image 178
David Avatar answered Oct 15 '22 14:10

David


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.

like image 24
Dustin Hodges Avatar answered Oct 15 '22 15:10

Dustin Hodges