ASP.NET: Get a strongly typed reference to a parent ASCX control

I have a user control (Dashboard.ascx) which contains a child control (DashboardChild.ascx).

From the child control, I would like to get a strongly typed reference to the parent to set a couple properties on the parent (Dashboard.ascx).

One idea that came to mind is to define a reference in my DashboardChild.ascx and on Page Load assign the parent to the child:

Dashboard.ascx

protected void Page_Load(object sender, EventArgs e)
{
    DasbhardChild.DashboardParent = this;
}

DashboardChild.ascx

 <%@ Register Src="~/Home/Dashboard.ascx" TagPrefix="uc1" TagName="Dashboard" %>   

// Code Behind
public Dashboard DashboardParent { get; set; }

protected void btnRun_Click(object sender, EventArgs e)
{
    DashboardParent.AdditionalInfo = "ABC";
}

However, this doesn't work as I get a runtime error: Circular file references are not allowed.

Any other ideas of how to get a strongly typed reference to a parent from a child?

1 answer

  • answered 2018-01-12 07:57 wazz

    Best not to work backwards, up the tree. Remember, when the page renders, the only thing rendered on the page is html.

    On the aspx page:

    Control DashboardChild = null;
    bool c = Dashboard.Controls.Contains(DashboardChild); // returns false.
    

    The code won't find a control on the page, only html, whatever is in the child control - not the control itself.

    Also see first answer here (first paragraph): Nested User Controls - how to best get a reference to an ancestor control