Using FindControl with Master Pages

How to modify a property of a control located in a Master Page from a content page by exposing a property from the Master Page. You have an alternative here. If you need to modify a control in a Master Page, you can use the FindControl() method in a content page.

ASPXMasterPage.master

<%@ Master Language=”C#” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml” >
<head id=”Head1” runat=”server”>
<style type=”text/css”>
html
{
background-color:silver;
}
.content
{
margin:auto;
width:700px;
background-color:white;
padding:10px;
}
h1
{
border-bottom:solid 1px blue;
}
</style>
<title>Find Master</title>
</head>
<body>
<form id=”form1” runat=”server”>
<div class=”content”>
<h1><asp:Literal ID=”ltlPageTitle” runat=”server” /></h1>
<asp:contentplaceholder id=”ContentPlaceHolder1” runat=”server” />
</div>
</form>
</body>
</html>

The content page modifies the Text property of the Literal control located in the Master Page. The content page uses the FindControl() method to retrieve the Literal control from the Master Page.

ASPXContent.aspx

<%@ Page Language=”C#” MasterPageFile=”~/ASPXMasterPage.master” %>
<script runat=”server”>
void Page_Load()
{
if (!Page.IsPostBack)
{
Literal ltlPageTitle = (Literal)Master.FindControl(“ltlPageTitle”);
ltlPageTitle.Text = “The Web Page Title”;
}
}
</script>
<asp:Content ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1” Runat=”Server”> </asp:Content>

The FindControl() method enables you to search a naming container for a control with a particular ID. The method returns a reference to the control.
Tags: ,
Hot on Web:


About author