//use this if your UserControl is in the same web directory this.MyControlHost.UserControlPath = "MyUserControl.ascx"; //use this if your UserControl is in another web directory this.MyControlHost.UserControlPath = "~/MyDirectory/MyUserControl.ascx";Here's the part I missed. This overridden property needs to be in your UserControl base class:
public override string UniqueID { get { if (this.Parent.Parent != null) return this.Parent.Parent.UniqueID + "ctl0"; else return base.UniqueID; } }And here's the DynamicControlHost ...
using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace YourNameSpaceHere { public class DynamicControlHost : System.Web.UI.UserControl { #region Declarations protected string m_UserControlPath = ""; protected System.Web.UI.WebControls.Panel WorkBox; #endregion #region Properties public string UniqueKey { get {return this.UniqueID + "DynamicControl";} } public string UserControlPath { get { if (this.m_UserControlPath.Length == 0 && Request.Form[this.UniqueKey] != null) this.m_UserControlPath = Request.Form[this.UniqueKey]; return this.m_UserControlPath; } set { if (this.WorkBox.Controls.Count > 0) { // If a control is already instantiated, and it's not the same one that's // currently being requested, remove it before adding the new one if (this.UserControlPath != value) { this.WorkBox.Controls.Remove(this.WorkBox.Controls[0]); this.WorkBox.Controls.Add(Page.LoadControl(value)); this.m_UserControlPath = value; } } else { this.WorkBox.Controls.Add(Page.LoadControl(value)); this.m_UserControlPath = value; } } } public Control UserControl { get { if (this.WorkBox.Controls.Count > 0) return this.WorkBox.Controls[0]; else return null; } } #endregion #region Page Init / Load private void Page_Init(object sender, System.EventArgs e) { // If it's a PostBack, change the ID of this control to what it was previously if (this.Page.IsPostBack && this.UserControlPath.Length != 0) this.WorkBox.Controls.Add(Page.LoadControl(this.UserControlPath)); } private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } #endregion #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); this.Init += new System.EventHandler(this.Page_Init); } #endregion #region Methods protected override void Render(System.Web.UI.HtmlTextWriter writer) { base.Render (writer); // (char)34 writer.Write("<input type=\"hidden\" name=\"" + this.UniqueKey + "\"value=\"" +this.UserControlPath + "\"/>"); } #endregion } }