James Andrew Smith
James Andrew Smith

Reputation: 1566

Accessing Master page control in ascx file

I have a master page file that contains a 2 menu's in a 2 panel controls. I also use a control to check if user is logged in and get the type of user.

Deppending on the type I want to show / hide the panel. The control itself is not referenced in the master page but dynamically through the CMS System.

I want to use findcontrol in the user control to find the panel control in the master page. I have tried different methods but all come back with null.

The content placeholder in the master page is asp:Content runat="server" ContentPlaceHolderID="PHMainBlock"

and the control is called asp:Panel ID="NormalUser" runat="server"

I have tried using the code....

Panel ph = (Panel)Page.Master.FindControl("NormalUser");
ph.Visible = false;

but brings back null, any help?

thanks..

Upvotes: 2

Views: 6955

Answers (4)

Mark
Mark

Reputation: 1537

Here's how I do something similar and it works fine:

if (Page.Master != null)
{
    var tempPanel = Page.Master.FindControl("MessagePanel") as UpdatePanel;
    if (tempPanel != null)
        tempPanel.Visible = true;


    var temp = Page.Master.FindControl("MessageForUser") as MessageToUser;
    if (temp != null)
        temp.PostWarningMessage(message, msgInterval);
}

However, I have "MessagePanel" and "MessageForUser" as controls right above the ContentPlaceHolder. Here's my markup:

<asp:UpdatePanel runat="server" Visible="true" ID="MessagePanel" >
    <ContentTemplate>
        <msg:MainMessage ID="MessageForUser" runat="server" Visible="true" />  
        <br />
    </ContentTemplate>
</asp:UpdatePanel>
<asp:ContentPlaceHolder ID="cphContent" runat="server" Visible="true">              
</asp:ContentPlaceHolder>

If you have your Panel inside of a tag, then you should be able to reference the panel without needing Page.Master.FindControl.

Upvotes: 1

Olivier De Meulder
Olivier De Meulder

Reputation: 2501

Because the Panel control is inside a ContentPlaceHolder control, you must first get a reference to the ContentPlaceHolder and then use its FindControl method to locate the TextBox control.

ContentPlaceHolder mpContentPlaceHolder;
Panel pn;
mpContentPlaceHolder = (ContentPlaceHolder)Master.FindControl("PHMainBlock");
if(mpContentPlaceHolder != null)
{
    pn = (Panel) mpContentPlaceHolder.FindControl("NormalUser");
    pn.Visible = false;
}

http://msdn.microsoft.com/en-us/library/xxwa0ff0.aspx

Upvotes: 1

Kevin Main
Kevin Main

Reputation: 2344

You could create a public property in you Master Page i.e

public bool ShowPanel
{
    set
    {
        NormalUser.Visible = value;
    }
}

And call it like this

if (Page.Master is NameOfMasterPage)
{
    ((NameOfMasterPage)Page.Master).ShowPanel = false;
}

Upvotes: 4

HW90
HW90

Reputation: 1983

One way would be to solve this problem with javascript (jquery):

$('.NormalUser').hide();

http://api.jquery.com/hide/

Upvotes: 0

Related Questions