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.
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";
Rick Strahl has a good explanation (and sample code) here - http://www.west-wind.com/Weblog/posts/5127.aspx
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With