Controls added in the designer are null during Page_Load
        Posted  
        
            by mwright
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by mwright
        
        
        
        Published on 2010-03-24T17:33:37Z
        Indexed on 
            2010/03/24
            17:53 UTC
        
        
        Read the original article
        Hit count: 418
        
All of the names below are generic and not the actual names used.
I have a custom UserControl with a Panel that contains a a couple Labels, both .aspx controls.
.aspx:
<asp:Panel runat="server">
    <asp:Label ID="label1" runat="server">
    </asp:Label>
</asp:Panel>
<asp:Panel runat="server">
    <asp:Label ID="label2" runat="server">
    </asp:Label>
</asp:Panel>
Codebehind:
private readonly Object object;
protected void Page_Load(object sender, EventArgs e)
{
    // These are the lines that are failing
    // label1 and label2 are null
    label1.Text = object.Value1;
    label2.Text = object.Value2;
}
public ObjectRow(Object objectToDisplay)
{
    object = objectToDisplay;
}
On another page, in the code behind, I create a new instance of the custom user control.
protected void Page_Load(object sender, EventArgs e)
{
    CustomControl control = new CustomControl(object);
}
The user control takes the parameter and attempts to set the labels based off of the object passed in.
The labels that it tries to assign the values to are however, null.
Is this an ASP.net lifecycle issue that I'm not understanding? My understanding based on the Microsoft ASP.net lifecycle page was that page controls were available after the Page_Initialization.
What is the proper way to do this? Is there a better way?
© Stack Overflow or respective owner