ASP.Net - C# - Update Content Label Text From Master Page

The following code snippet demonstrates how to update the Text property of a Label control located in a page which uses a master page from within the master page code behind file.
  1. // MasterPage.master
  2.  
  3. <%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
  4.  
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  6.  
  7. <html xmlns="http://www.w3.org/1999/xhtml">
  8. <head runat="server">
  9.     <title></title>
  10. </head>
  11. <body>
  12.     <form id="form1" runat="server">
  13.     <div>
  14.         <asp:LinkButton ID="LinkButton1" runat="server" Text="Click Me" OnClick="LinkButton1_Click" />
  15.         <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server" />
  16.     </div>
  17.     </form>
  18. </body>
  19. </html>
  20.  
  21. // MasterPage.master.cs
  22.  
  23. using System;
  24. using System.Collections.Generic;
  25. using System.Linq;
  26. using System.Web;
  27. using System.Web.UI;
  28. using System.Web.UI.WebControls;
  29.  
  30. public partial class MasterPage : System.Web.UI.MasterPage
  31. {
  32.     protected void LinkButton1_Click(object sender, EventArgs e)
  33.     {
  34.         if (ContentPlaceHolder1.FindControl("Label1") != null)
  35.         {
  36.             Label lbl = (Label)ContentPlaceHolder1.FindControl("Label1");
  37.             lbl.Text = "Label updated from master page";
  38.         }
  39.     }
  40. }
  41.  
  42.  
  43. // Default.aspx
  44.  
  45. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" MasterPageFile="~/MasterPage.master" %>
  46. <asp:Content ID="Content" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
  47.     <asp:Label ID="Label1" runat="server" />
  48. </asp:Content>

No comments:

Post a Comment