【问题标题】:Programmatically added User Control does not create its child controls以编程方式添加的用户控件不会创建其子控件
【发布时间】:2010-10-09 07:21:48
【问题描述】:

我的项目中有一个用户控件 (.ascx),我在页面的 Page_Load 事件处理程序中以编程方式将其添加到页面,如下所示:

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

当我尝试从控件本身访问控件的子控件时,它们不存在。

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

  base.DataBind();
}

如何访问用户控件的子控件?我已经尝试将 EnsureChildControls() 调用添加到我的 DataBind() 覆盖中,但这似乎没有任何区别。

【问题讨论】:

    标签: c# asp.net user-controls


    【解决方案1】:

    您需要使用 LoadControl 来加载它,而不仅仅是实例化类。 LoadControl 在幕后执行“魔术”以将所有内容绑定并实例化前端。

    【讨论】:

      【解决方案2】:

      编辑:我误解了你的问题,

      试试这个把你的 UserControl 添加到你的页面:

      UserControl uc = new UserControl();
      uc.LoadControl(Server.MapPath("MyUserControl.ascx");
      this.Controls.Add(uc);
      

      【讨论】:

      • 只需在页面上使用 LoadControl。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 1970-01-01
      相关资源
      最近更新 更多