Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access master page control from usercontrol of aspx which enclosed in master page

I have a aspx page which enclosed in master page. My aspx page have user control (ASCX) from user control I am opening a pop up in which I want to get master page controls how can I do it.

like image 405
pra Avatar asked Oct 31 '25 09:10

pra


1 Answers

ASP.NET has internal property for each page 'Master'. From usercontrol you can travese the stack backwards to Usercontrols parent > Page > Master. If the control in master page is outside any contentplace holders, you can get the control using FindControl method. If it is inside any content place holders, you have to traverse to the content place holder and then you can find the control. The example is below.

MASTER

<body>
    <form id="form1" runat="server">
    <div>
       <asp:Label ID="lblVal" runat="server" Text="MasterLabel"></asp:Label>
        <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>

CONTENT PAGE

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <test:uc ID="test" runat="server" />
</asp:Content>

USER CONTROL

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

USERCONTROL CODE BEHIND

 protected void Page_Load(object sender, EventArgs e)
    {
        MasterPage mstr = this.Parent.Page.Master as MasterPage;
        Label1.Text = (mstr.FindControl("lblVal") as Label).Text;
    }

In my case the Label in master page is outside content page.

like image 162
clklachu Avatar answered Nov 02 '25 13:11

clklachu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!