Pitfalls of using LoadControl in a Load event

I use the LoadControl method in the Load event quite widely. However, I had no problems, I'm afraid the MSDN documentation says:

When you load a control into a container control, the container raises all the added control events until it catches up to the Current event. However, the added control does not catch up with reverse data processing . For additional control to participate in reverse data processing, including verification, control should be added in the Init event, and not in the Load event.

What does it mean?

Are there any other errors when loading the control in the Load event?

+4
source share
2 answers

This bit of the MSDN documentation is (mostly) wrong. As you discovered, reverse processing and validation are performed even if you dynamically add controls to the Load event.

The following are the life cycle steps for an ASP.NET page that are relevant to this issue:

  • Raise the Init event.
  • Postbacks: download status and download status.
  • Postbacks: Download published form data (first attempt).
  • Raise the Load event.
  • Postbacks: Download published form data (second attempt).
  • Postbacks: check the form and raise the postback event.

The documentation is correct when it says that "the added control does not catch up with the processing of the postback data." But he overlooks the fact that there are two attempts to load hosted form data, once before the Load event and once after. Thus, if you dynamically add a control to the Load event, it will be filled with the published form data at the time of the postback event (for example, submitButton_Click ).

As far as I can tell, here's the main difference and a potential trap:

  • If you dynamically add a control to Init , you can access its published form data in Load .
  • If you dynamically add a control to Load , you need to wait until the postback event (or directly access the HttpRequest.Form collection).
+3
source

This means that by the time Control_Load executed, the Control_Load loop had come and gone. If you have a control that needs to be involved in the postback, you need to load it earlier, so it is recommended that you use docs in the Init override instead.

If your controls are not involved in the postback, then you're fine.

0
source

Source: https://habr.com/ru/post/1399098/


All Articles