儿童通过控制编程LoadControl加载用户控件的时候是空的(类型,对象[])超负荷 [英] 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);
}
与此构造:
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?
推荐答案
这是由设计。一个.ascx文件实际上是从继承code-behind类,所以的.ascx是code隐藏类的派生类型。
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.
这意味着,当你使用 LoadControl加载父code-behind类(类型,对象[])
方法,它的实例中定义的父类在code-后面,而不是派生的.ascx类,它包含的子控件。
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.
如果您使用 Page.LoadControl(串)
过载,它将工作如你所愿,因为它可以正确地找到模板,找到编译的.ascx类,并加载它。
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.
另一种方法是使用code-背后,而不是标记来实例化您的.ascx文件的所有控件。
The other alternative is to instantiate all the controls in your .ascx file by using the code-behind instead of the markup.
这篇关于儿童通过控制编程LoadControl加载用户控件的时候是空的(类型,对象[])超负荷的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!