I use LoadControl method in Load event quite extensively. However I haven’t observed any problems yet, I’m afraid of what MSDN documentation says:
When you load a control into a container control, the container raises all of the added control's events until it has caught up to the current event. However, the added control does not catch up with postback data processing. For an added control to participate in postback data processing, including validation, the control must be added in the Init event rather than in the Load event.
What does it actually mean?
Are there any other pitfalls when loading a control in the Load event?
That bit of MSDN documentation is (mostly) wrong. As you've discovered, postback data processing and validation work even if you dynamically add controls in the Load
event.
Here are the stages of the ASP.NET page life cycle that are relevant to this question:
Init
event.Load
event.The documentation is correct when it says that "the added control does not catch up with postback data processing". But it overlooks the fact that there are two attempts to load posted form data, once before the Load
event and once after. Thus, if you dynamically add a control in the Load
event, it will be populated with posted form data by the time the postback event (such as submitButton_Click
) occurs.
As far as I can tell, here's the main difference and potential pitfall:
Init
, you can access its posted form data in Load
.Load
, you have to wait until the postback event (or else access the HttpRequest.Form
collection directly).It means that by the time Control_Load
executes, the postback cycle has come and gone. If you have a control that needs to participate in postback, you need to load it before, so that's why the docs recommend doing it in the Init
override instead.
If your controls don't participate in postback then you're OK.
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