All controls are null within usercontrol

后端 未结 4 2216
醉酒成梦
醉酒成梦 2021-02-18 13:27

I have a UserControl which uses a UserControl, among other controls.

In the ascx file I have the following code:

<%@ Register TagPrefix=         


        
4条回答
  •  被撕碎了的回忆
    2021-02-18 14:28

    The issue here is usually due the the load mechanics of user controls, they load after the page typically. So as a result the controls have not yet been initialized on your usercontrol (causing the null ref) during the containing page_load method. One way to work around this is to just create and set a property on the usercontrol and have the usercontrol wire-up/populate its own UI in its Page_Load method.

    Something like this:

    //Page
    protected void Page_Load(object sender, EventArgs e)
    {
        test.Text = "Hello World!";
    }
    
    //User Control
    public string Text {get; set;}
    
    protected void Page_Load(object sender, EventArgs e)
    {
        lblTest.Text = Text;
    }
    

提交回复
热议问题