Tuesday, December 11, 2012

Access Content Page Controls from Master Page.

Create a master page.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <asp:ContentPlaceHolder id="head" runat="server">
    <form id="form1" runat="server">
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

Now create a content page and add a label control.

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="MasterPage.aspx.cs" Inherits="MasterPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:Label ID="Label1" runat="server" Text="This is Content Page Label"></asp:Label>

We need to get the label text from the master page. Below method in the master page will access the content page through the ContentPlaceHolderID and get the label control text.

protected void Page_Load(object sender, EventArgs e)

        if (!Page.IsPostBack)

    private void AccessContentPage()
       Label lbl=(Label)ContentPlaceHolder1.FindControl("Label1");// Cast the control to a label
       if (lbl != null)
           Response.Write("Accessed From Master Page: "+lbl.Text);

Accessed From Master Page: This is Content Page Label
This is Content Page Label

No comments:
Write comments
Recommended Posts × +