Programmatically added User Control does not create its child controls

一个人想着一个人 提交于 2019-12-24 01:49:26

问题


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();
}

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.


回答1:


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.




回答2:


EDIT : I missunderstood your question,

try this to add your UserControl to your page :

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


来源:https://stackoverflow.com/questions/577353/programmatically-added-user-control-does-not-create-its-child-controls

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!