When you use a content page based on a previously created master page, there is sometimes a want to access attributes of control defined in the master page, such as a label, hyperlink, or dropdownlist. By default, there is no way to easy way to access the those controls. However, using the FindControl function will allow access to those controls. First part of the example is the basic master page code:
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>Accessing Master Page Controls</title>
<asp:ContentPlaceHolder ID=”head” runat=”server”>
</asp:ContentPlaceHolder>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:ContentPlaceHolder ID=”ContentPlaceHolder1″ runat=”server”></asp:ContentPlaceHolder>
<asp:Label ID=”lblUserName” runat=”server” Text=”Victor Chen”></asp:Label>
</div>
</form>
</body>
</html>
Next, is a relevant snippet from the content page’s code behind file that will access a label defined earlier in the master page.
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String username = ((Label)Master.FindControl(”lblUserName“)).Text;
}
}
The Master property listed in red will access the master page as defined in the <%@ Page MasterPageFile> property defined in the content page.
The FindControl function of the Master property takes one string input. The string input is the id of the control defined in the master page. In this case, the label id in the master page is defined as lblUserName.
Finally, the FindControl function returns an object, so we must cast the object back to a Label. Once back to a label, the text of the label can be extracted by accessing the Text property.
This entry was posted on Friday, March 14th, 2008 at 3:37 am and is filed under C#, Visual Studio. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply