Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pitfalls of using LoadControl in the Load event

Tags:

asp.net

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?

like image 255
Jakub Linhart Avatar asked Feb 29 '12 22:02

Jakub Linhart


2 Answers

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:

  1. Raise the Init event.
  2. Postbacks: Load view state and control state.
  3. Postbacks: Load posted form data (first attempt).
  4. Raise the Load event.
  5. Postbacks: Load posted form data (second attempt).
  6. Postbacks: Validate the form and raise the postback 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:

  • If you dynamically add a control in Init, you can access its posted form data in Load.
  • If you dynamically add a control in Load, you have to wait until the postback event (or else access the HttpRequest.Form collection directly).
like image 200
Michael Liu Avatar answered Nov 03 '22 03:11

Michael Liu


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.

like image 26
kprobst Avatar answered Nov 03 '22 03:11

kprobst