Wednesday, July 25, 2007

Accessing Master Page Controls via Content Pages

There are a couple of ways to access the controls of Master Pages in ASP.NET 2.0 from within your content pages. You can do this in a non-strongly typed manner or a strongly type manner. I will provide a sample below that demonstrates each approach.

Non-Strongly Typed

Lets say your Master Page contains a Label that displays the current Date. Within your content page use the FindControl method to locate the control in the Master Page whose property you want to access. Note you must perform an explicit cast.

Label lbl = (Label)Master.FindControl("DateLabel");
lbl.Text = DateTime.Today.ToLongDateString();

Strongly Typed

In the code-behind of your Master Page create a property that accesses the control you want to manipulate.

public string GetCurrentDate
get { return DateLabel.Text; }
set { DateLabel.Text = value; }

In the HTML source of your content page add the following beneath the Page <%@ Page %><%@ Page %><%@ Page %>directive. Add MasterType before TypeName.

< typename="Site">

Replace "Site" with the class name of your Master Page. You could also re-write the above using VirtualPath in place of TypeName. NOTE: Blogger will not display the percent signs that are between the <> as well it also Strips out the MasterType Directive.

To do this just replace the MasterPage.master with the name of your Master Page.

Finally in the code-behind of your content page you can set the DateLabel to the current date on your Master Page as below:

this.Master.GetCurrentDate = DateTime.Today.ToLongDateString();

Thursday, July 12, 2007