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).
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.
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.
As a general rule of thumb add them as soon as you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With