Wednesday 30 January 2013

C# ASP.NET - How to access controls in master page from child page

Watch whole example on YouTube.

3 ways to do that
1. add text box to master page
__________________________________________________________________________
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
 
        </asp:ContentPlaceHolder>
    </div>
    </form>
2. In code behind of the master page add the following property
        public TextBox TextBox
        {
            get { return this.TextBox1; }
        }
3. In child page add the following code:
        protected void Page_Load(object sender, EventArgs e)
        {
             Site1 m = Master as Site1;
             m.TextBox.Text = "aaaaaaaaaaaaa";
        }
__________________________________________________________________________
Another - better example
__________________________________________________________________________
1. add text box to master page
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
 
        </asp:ContentPlaceHolder>
    </div>
    </form>
2. In code behind of master page add the following property
        public TextBox TextBox
        {
            get { return this.TextBox1; }
        }
3. Add the following to html of child page
<%@ MasterType virtualpath="~/Site1.master" %>
4. In child page code behind add the following code
        protected void Page_Load(object sender, EventArgs e)
        {
             Master.TextBox.Text = "BBB:";
        }
__________________________________________________________________________
By referenece
__________________________________________________________________________
1. add text box to master page
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
 
        </asp:ContentPlaceHolder>
    </div>
    </form>
2.In child page code behind add the following code
     protected void Page_Load(object sender, EventArgs e)
        {
            TextBox tb;
            tb = (TextBox)Master.FindControl("TextBox1");
            tb.Text = "BBB";
        }

No comments:

Post a Comment