ASP.NET Dynamic UserControl Reference Parent Page Custom Type

By Robbe Morris

This tip shows how to access the parent page and master page from inside a dynamically loaded UserControl in ASP.NET. It enables the UserControl to access custom methods and properties of the parent page as well as the master page even if the page inherits from a custom class instead of System.Web.UI.Page.

// Parent Page Declaration:

public partial class MyParentPage : MyCustomBasePage
{
   protected void Page_Load(object sender, EventArgs e)
   {
       var control = LoadControl("~/MyUserControl.ascx");
       var row = new TableRow();
       var cell = new TableCell();
       cell.Controls.Add(control);
       row.Cells.Add(cell);
       this.UserControlContainer.Rows.Add(row);
   }
   public void SomeTestMessage(string text)
   {
     Response.Write(text);
   }
}

// Child User Control Declaration:

public partial class MyUserControl : System.Web.UI.UserControl
{
   MyParentPage _parentPage = null;

   protected void Page_Load(object sender, EventArgs e)
   {
         _parentPage = this.Page as MyParentPage;
         if (_parentPage == null) return;  // Parent Page Type Was Not MyParentPage;
         _parentPage.SomeTestMessage("called from user control");
   }
}

ASP.NET Dynamic UserControl Reference Parent Page Custom Type  (1805 Views)