When creating a web control should you override OnLoad or implement Page_Load

前端 未结 8 2063
南笙
南笙 2020-12-19 02:25

When you create a new web user control in visual studio it by default adds the Page_Load event. What is the advantage to using this rather than overriding the base On

相关标签:
8条回答
  • 2020-12-19 03:10

    I think there is one potentially significant difference in the two methods.

    What I am referring to is the ability to have control over the execution sequence.

    If you are overriding, you know when the base classes Load will take place because you are calling it. This provides more control, but probably is a bad thing as many will argue.

    If you use event, you have no guarantee in terms of order of call. This forces you to write Load event which should be agnostic about what super classes are doing during Load phase. I think this would be the preferred approach and maybe that is why VS auto-generated code is this way.

    0 讨论(0)
  • 2020-12-19 03:12

    i think it's the same. IMHO, With Events, you have a bit of more flexibility, because you can happen more than one listener to your event!

    0 讨论(0)
  • 2020-12-19 03:21

    The OnLoad method should be the place where the Load event is raised. I personally always try to handle the event unless I need to do extra processing around raising the event.

    I recommend handling the event itself under normal circumstances.

    0 讨论(0)
  • 2020-12-19 03:23

    Read the section called: "Binding Page Events" on the MSDN page titled: "ASP.NET Web Server Control Event Model" (link to the page) There are some useful statements like these:

    One disadvantage of the AutoEventWireup attribute is that it requires that the page event handlers have specific, predictable names. This limits your flexibility in how you name event handlers. Another disadvantage is that performance is adversely affected, because ASP.NET searches for methods at run-time. For a Web site with high traffic volumes, the impact on performance could be significant.

    (AutoEventWireup flag turns on such methods like Page_Load)

    0 讨论(0)
  • 2020-12-19 03:24

    Even though you're inheriting from UserControl, I think you should stay away from overriding the protected methods if you don't have to. The Page_Load is there to make it easier for you to add the code that's specific to your UserControl.

    Only override OnLoad if you need absolute control over when(/if) the Load event is fired (which should be rare, IMO).

    0 讨论(0)
  • 2020-12-19 03:29

    You may find this article on the page lifecycle from Microsoft useful.

    0 讨论(0)
提交回复
热议问题