LoadControl vs Construct ASP.Net Control

后端 未结 2 2138
一生所求
一生所求 2021-02-14 19:41

I have a question why we can only add dynamic control using LoadControl. For example:

public partial class wucReportParam : System.Web.UI.UserControl
{
    prote         


        
相关标签:
2条回答
  • 2021-02-14 20:07

    Apparently, using LoadControl with typeof (or GetType) has the same problem as using 'new' where the child controls are not initialized. Using LoadControl with a string to the ASCX file works.

    Does not initialize child controls.

    LoadControl(typeof(MyReport), null);
    

    Works!

    LoadControl("Report.ascx");
    
    0 讨论(0)
  • 2021-02-14 20:10

    When dynamically loading a user control, it is important to ensure that the standard ASP.NET page event pipeline is initiated and progresses normally. When you use the new operator to create an instance of a user control, that user control is not properly added to ASP.NET's event system. If the events (Init, Load, PreRender, etc.) to not fire, then your control will never function properly. That is why it is necessary to use LoadControl, as that will make sure that the instance of your user control is created properly and attached to ASP.NET.

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