Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Child Controls are null when loading User Control programmatically via LoadControl(Type, object[]) overload

Tags:

c#

asp.net

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?

like image 605
ryudice Avatar asked Feb 11 '10 00:02

ryudice


1 Answers

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.

like image 143
womp Avatar answered Nov 04 '22 09:11

womp