Thursday, 20 February 2014

How to access content page controls from master page in ASP.NET

Here I will explain how to access or get content or child page controls from master page in asp.net.

To get child or content page control values in master page first write the following code in master page :

MasterPage.Master
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Master Page with Controls</title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
</head>
<body>
<form id="form1" runat="server">
MasterPage Label:
<asp:Label ID="lblMaster" runat="server" />
MasterPage Textbox:
<asp:textbox ID="txtMaster" runat="server" />
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</form>
</body>

</html>

C# Code (MasterPage)

using System;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Label cotentlbl = (Label)ContentPlaceHolder1.FindControl("lblContent");
TextBox contenttxt = (TextBox)ContentPlaceHolder1.FindControl("txtContent");
lblMaster.Text = cotentlbl.Text;
txtMaster.Text = contenttxt.Text;
}
}

After that write the code in Content Page Default.aspx

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

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<fieldset id="fld">
<legend><b>Content Page</b></legend>
Content Page Label Value:
<asp:Label ID="lblContent" Text="Sample Content Page label Control" runat="server"/>
<br />
Content Page Textbox Value:
<asp:Textbox ID="txtContent" Text="Sample Content Page Textbox Control" runat="server"/>
</fieldset>

</asp:Content>

No comments:

Post a Comment