Child Controls are null when loading User Control programmatically via LoadControl(Type, object[]) overload
I'm loading a user control programatically like this:
protected void Page_Load(object sender, EventArgs e)
{
// LinqDataSource1.TableName = string.Format("{0}s", _table.Context.Mapping.GetMetaType(_type).Name);
_control = Page.LoadControl(typeof(CatalogoGenerico), new object[] { typeof(CTG_ENT_ENTIDAD) }) as CatalogoGenerico;
PlaceHolder1.Controls.Add(_control);
}
with this constructor:
public CatalogoGenerico(Type type):this()
{
_db = new DataClasses1DataContext();
_type = type;
开发者_开发百科
}
The problem I have is that all the controls in my user controls are null, is there something else I have to do to load the child controls?
This is by design. An .ascx file actually inherits from the code-behind class, so the .ascx is a derived type of the code-behind class.
This means that when you load the parent code-behind class using the LoadControl(Type, object[])
method, it's instantiating the parent class defined in the code-behind, and not the derived .ascx class which contains the child controls.
If you use the Page.LoadControl(string)
overload, it will work as you wish, as it can properly find the template, find the compiled .ascx class, and load it.
The other alternative is to instantiate all the controls in your .ascx file by using the code-behind instead of the markup.
精彩评论