通过LoadControl(Type,object [])重载以编程方式加载用户控件时,子控件为null

时间:2010-02-11 00:20:56

标签: c# asp.net

我正在以编程方式加载用户控件:

        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;

    }

我遇到的问题是我的用户控件中的所有控件都是null,是否还需要加载子控件?

1 个答案:

答案 0 :(得分:17)

这是设计的。 .ascx文件实际上是从代码隐藏类继承的,因此.ascx是代码隐藏类的派生类型。

这意味着当您使用LoadControl(Type, object[])方法加载父代码隐藏类时,它将实例化代码隐藏中定义的父类,而不是包含子控件的派生.ascx类。 / p>

如果您使用Page.LoadControl(string)重载,它将按您的意愿工作,因为它可以正确地找到模板,找到已编译的.ascx类,并加载它。

另一种方法是使用代码隐藏而不是标记来实例化.ascx文件中的所有控件。

相关问题