Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access a content control in C# when using Master Pages

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.

like image 454
Guillaume Gervais Avatar asked Jun 29 '09 20:06

Guillaume Gervais


3 Answers

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";
like image 180
CRice Avatar answered Oct 15 '22 19:10

CRice


Rick Strahl has a good explanation (and sample code) here - http://www.west-wind.com/Weblog/posts/5127.aspx

like image 35
Duncan Avatar answered Oct 15 '22 21:10

Duncan


Nothing to do different. Just write this code on child page to access the master page label control.

Label lblMessage = new Label();
lblMessage = (Label)Master.FindControl("lblTest");
lblMessage.Text = DropDownList1.SelectedItem.Text;
like image 44
Dharmendra H Gupta Avatar answered Oct 15 '22 20:10

Dharmendra H Gupta