Access a content control in C# when using Master Pages

Guillaume Gervais picture Guillaume Gervais · Jun 29, 2009 · Viewed 41k times · Source

Good day everyone,

I am building a page in ASP.NET, and using Master Pages in the process.

I have a Content Place Holder name "cphBody" in my Master Page, which will contain the body of each Page for which that Master Page is the Master Page.

In the ASP.NET Web page, I have a Content tag (referencing "cphBody") which also contains some controls (buttons, Infragistics controls, etc.), and I want to access these controls in the CodeBehind file. However, I can't do that directly (this.myControl ...), since they are nested in the Content tag.

I found a workaround with the FindControl method.

ContentPlaceHolder contentPlaceHolder = (ContentPlaceHolder) Master.FindControl("cphBody");
ControlType myControl = (ControlType) contentPlaceHolder.FindControl("ControlName");

That works just fine. However, I am suspecting that it's not a very good design. Do you guys know a more elegant way to do so?

Thank you!

Guillaume Gervais.

Answer

CRice picture CRice · Jun 30, 2009

I try and avoid FindControl unless there is no alternative, and there's usually a neater way.

How about including the path to your master page at the top of your child page

<%@ MasterType VirtualPath="~/MasterPages/PublicUI.Master" %>

Which will allow you to directly call code from your master page code behind.

Then from your master page code behind you could make a property return your control, or make a method on the master page get your control etc.

public Label SomethingLabel
{
    get { return lblSomething; }
}
//or
public string SomethingText
{
    get { return lblSomething.Text; }
    set { lblSomething.Text = value; }
}

Refers to a label on the master page

<asp:Label ID="lblSomething" runat="server" />

Usage:

Master.SomethingLabel.Text = "some text";
//or
Master.SomethingText = "some text";