Ответ 1
То, что я сделал, это использовать метод Page.LoadControl в Page_Init, чтобы добавить пользовательский элемент управления к владельцу места на странице.
protected void Page_Init(object sender, EventArgs e)
{
//MyControl is the Custom User Control with a code behind file
MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");
//UserControlHolder is a place holder on the aspx page where I want to load the
//user control to.
UserControlHolder.Controls.Add(myControl);
}
Это отлично работает для меня.
Вот код для динамически загружаемого пользовательского элемента управления:
MyControl.ascx.cs
public partial class MyControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
LiteralControl lit = new LiteralControl("Test Literal Control");
Page.Controls.Add(lit);
}
protected void Page_Load(object sender, EventArgs e)
{
whatever.Visible = true;
if (IsPostBack)
{
whatever.Visible = false;
}
}
}