asp.net.ph

Skip Navigation LinksHome > ASP.NET Web Forms > ASP.NET Master Pages > Referencing Master Page Content

Referencing Master Page Content

ASP.NET Web Forms   ASP.NET Master Pages


You can write code in content pages that references properties, methods, and controls in the master page, with some restrictions. The rule for properties and methods is that you can reference them if they are declared as public members of the master page. This includes public properties and public methods. You can reference controls on the master page independently of referencing public members.

To reference a public member on the master page

  1. Add a @ MasterType directive in the content page. In the directive, set the VirtualPath attribute to the location of the master page, as in this example:
    <%@ MasterType virtualpath="~/Masters/Master1.master" %>

    This directive causes the content page’s Master property to be strongly typed.

  2. Write code that uses the master page’s public member as a member of the Master property, as in this example, which assigns the value of a public property named CompanyName from the master page to a text box on the content page:

To reference a control on the master page

  • Use the FindControl method, using the value returned by the Master property as the naming container.

The following code example shows how to use the FindControl method to get a reference to two controls on the master page, a TextBox control and a Label control. Because the TextBox control is inside a ContentPlaceHolder control, you must first get a reference to the ContentPlaceHolder and then use its FindControl method to locate the TextBox control.

void Page_Load ( ) {
   // gets a reference to a TextBox control inside a ContentPlaceHolder
   TextBox mpTextBox;
   ContentPlaceHolder mpContentPlaceHolder = 
      ( ContentPlaceHolder ) Master.FindControl ( "ContentPlaceHolder1" );
   if ( mpContentPlaceHolder != null ) {
      mpTextBox = ( TextBox ) mpContentPlaceHolder.FindControl ( "TextBox1" );
      if ( mpTextBox != null ) {
         mpTextBox.Text = "TextBox found!";
      }
   }
   // gets a reference to a Label control that not in a ContentPlaceHolder
   Label mpLabel = ( Label ) Master.FindControl ( "masterPageLabel" );
   if ( mpLabel != null ) {
      Label1.Text = "Master page label = " + mpLabel.Text;
   }
}
  C# VB

See Also

Events in Master and Content Pages   Working with Master Pages Programmatically



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note