Here I will explain how to access or get master page controls from child or content page in asp.net
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">
<div>
MasterPage Label:
<asp:Label ID="lblMaster" runat="server" Text="Sample master Page label Control"/>
MasterPage Textbox:
<td><asp:textbox ID="txtMaster" runat="server" Text="Sample Master Page Textbox Control"/>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
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">
<b>Content Page Label Value:</b>
<asp:Label ID="lblContent" runat="server"/>
<br />
<b>Content Page Textbox Value:</b>
<asp:Textbox ID="txtContent" runat="server"/>
</asp:Content>
C# Code(Default.aspx)
using System;
using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label masterlbl = (Label)Master.FindControl("lblMaster");
TextBox mastertxt = (TextBox) Master.FindControl("txtMaster");
lblContent.Text = masterlbl.Text;
txtContent.Text = mastertxt.Text;
}
}
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">
<div>
MasterPage Label:
<asp:Label ID="lblMaster" runat="server" Text="Sample master Page label Control"/>
MasterPage Textbox:
<td><asp:textbox ID="txtMaster" runat="server" Text="Sample Master Page Textbox Control"/>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
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">
<b>Content Page Label Value:</b>
<asp:Label ID="lblContent" runat="server"/>
<br />
<b>Content Page Textbox Value:</b>
<asp:Textbox ID="txtContent" runat="server"/>
</asp:Content>
C# Code(Default.aspx)
using System;
using System.Web.UI.WebControls;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Label masterlbl = (Label)Master.FindControl("lblMaster");
TextBox mastertxt = (TextBox) Master.FindControl("txtMaster");
lblContent.Text = masterlbl.Text;
txtContent.Text = mastertxt.Text;
}
}
No comments:
Post a Comment