以编程方式添加用户控件不会创建它的子控件 [英] Programmatically added User Control does not create its child controls

查看:166
本文介绍了以编程方式添加用户控件不会创建它的子控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目,我添加到页面编程在页面的Page_Load事件处理程序的用户控件(.ascx),像这样:

I have a user control (.ascx) in my project that I am adding to a page programmatically in the page's Page_Load event handler, like so:

Controls.Add(new MyProject.Controls.ControlWidget());
Databind();

当我试图从控制自身内部访问控件的子控件,它们不存在。

When I try to access the control's child controls from within the control itself, they do not exist.

public override void DataBind()
{
  myrepeater.DataSource = GetDataSource(); 
  // throws an exception because myrepeater is null

  base.DataBind();
}

我如何访问用户控件的子控件?我曾尝试加入EnsureChildControls()调用我的DataBind()重写,但似乎并没有发挥作用。

How do I access the user control's child controls? I have tried adding a call to EnsureChildControls() to my DataBind() override but that doesn't seem to make a difference.

推荐答案

您需要使用LoadControl加载它,不只是实例化类。 LoadControl没有神奇的幕后扳平的一切行动和实例化的前端。

You need to use LoadControl to load it, not just instantiate the class. LoadControl does "magic" behind the scenes to tie everything up and instantiate the front end.

这篇关于以编程方式添加用户控件不会创建它的子控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆