Friday 10 October 2008

How to: Inherit master page events, methods, properties in a child master page

The easiest way to access events, methods, or properties on a parent master page within a child master page is to use an interface.

Master Pages

Create all common functionlity in a parent master page i.e. Parent.master

Now create your child master page i.e Child.master with it's master page set to Parent.master

<%@ Master Language="C#" MasterPageFile="Parent.master" AutoEventWireup="true" CodeFile="Child.master.cs" Inherits="Child" %>

Interface

Create an interface with a property/method/event you wish to set at parent level and access at child level.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace PageInterfaces

{

public interface IMasterPage

{

string hello { get; set; }

}

}

Child.master

public partial class Parent : System.Web.UI.MasterPage, IMasterPage

{

public string hello { get; set; }

protected void Page_Load(object sender, EventArgs e)

{

hello = "Hello World!";

}

}

No comments: