Controls added in the designer are null during Page_Load Controls added in the designer are null during Page_Load asp.net asp.net

Controls added in the designer are null during Page_Load


When you create an instance of the code behind class of the user control, you don't create an instance of the user control. The actual user control is the class that is created from the markup in the .ascx file, and that class inherits from the code behind class.

If you want to create user controls dynamically, you use the Page.LoadControl method. It will create an instance of the user control where the code behind control references correspond to controls created from the markup:

CustomControl control = (CustomControl)Page.LoadControl("controls/CustomControl.ascx");

But that doesn't give you an opportunity to send parameters to the constructor, so you might want to use the overload that takes a type:

CustomControl control = (CustomControl)Page.LoadControl(typeof(CustomControl), new object[] { objectToDisplay } );

(I'm not sure what the type parameter should really be. Logically it should be the type of the .ascx page rather than the type of the code behind class.)


Use Register directive in your markup of the page/parent user control:

<%@ Register TagPrefix="wb" src="~/CustomControl.ascx" TagName="CustomControl" %><asp:CustomControl runat="server" />


You can try calling EnsureChildControls in the custom control's Page_Load handler, although AFAIK that shouldn't be strictly necessary.

When/where are you adding the custom control to the Controls collection?