Powered by Blogger.

Friday, February 14, 2014

access master page controls from content page in asp.net

In this post we will discuss how we can access master page controls in content pages in Asp.Net. Also you can check out my previous posts on:

- Body onload function in content page in asp.net

- Bind dropdownlist from enum in Asp.Net

- NuGet tutorial in Asp.Net

In this example, we have a Label control in the master page and in the content page we are going to retrieve the Label and we will write something to the control through the content page.

We can retrieve the master page control in the content page by using the FindControl method of Master class.

Master Page Code:
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Get Master Page control in content page</title>
    <asp:ContentPlaceHolder id="head" runat="server">
    <form id="form1" runat="server">
       Master Page: <asp:Label ID="lblMaster" runat="server" Text=""></asp:Label>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">       


Content Page Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default12 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            Label lbl = ((Label)Master.FindControl("lblMaster"));
            lbl.Text = "We are writting in the master page label !!!";


Similarly if you want to retrieve textbox, we can write like below:

TextBox lbl = ((TextBox)Master.FindControl("txtMaster"));