Sunday 10 May 2015

How to Read Access Get Set Master Page Controls from Child Page using Asp.Net C#

In this Article, i will explain how we can access or read Master page controls from Child Page or Content Page.
First Add some controls in Master Page to read from Child Page:
<div class="main">
      <asp:Label ID="lblMaster" runat="server" Text="Master Label"></asp:Label>
      <asp:TextBox ID="txtMaster" runat="server"  placeholder="Master Textbox" ></asp:TextBox>
      <asp:ContentPlaceHolder ID="MainContent" runat="server" />
    </div>

Add some Controls in Child Page:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
  <br />
  <hr />
  <asp:Button ID="btnGetMasterPageContent" runat="server" Text="Get Master Page Content" OnClick="btnGetMasterPageContent_Click" />
  <asp:Button ID="btnSetMasterPageContent" runat="server" Text="Set Master Page Content" OnClick="btnSetMasterPageContent_Click" />
  <br /><br />
  <asp:Label ID="lblChild" runat="server" Text="Child Label"></asp:Label>
  <asp:TextBox ID="txtChild" placeholder="Child Textbox" runat="server"></asp:TextBox>
</asp:Content>

Now Child Page Code behind:
protected void btnGetMasterPageContent_Click(object sender, EventArgs e)
    {
      Label lblMaster = (Label)Master.FindControl("lblMaster");
      TextBox txtMaster = (TextBox)Master.FindControl("txtMaster");

      if (lblMaster != null)
      {
        lblChild.Text = lblMaster.Text;
      }
      if (txtMaster != null)
      {
        txtChild.Text = txtMaster.Text;
      }
    }
    protected void btnSetMasterPageContent_Click(object sender, EventArgs e)
    {
      Label lblMaster = (Label)Master.FindControl("lblMaster");
      TextBox txtMaster = (TextBox)Master.FindControl("txtMaster");

      if (lblMaster != null)
        lblMaster.Text = lblChild.Text;
      if (txtMaster != null)
        txtMaster.Text = txtChild.Text;
    }


Note-Hope now you can Access Master Page Contents as well as can set also data from child page.

No comments:

Post a Comment