Can't access label in content place holder in master page

5.3k Views Asked by At

My master page contains this:

<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    <asp:Label ID="User" runat="server" Text="Welcome, " Visible="false"></asp:Label>
</asp:ContentPlaceHolder>

I'm trying to access the label like this:

Label welcomeLabel;
ContentPlaceHolder cPlaceHolder;            

cPlaceHolder = (ContentPlaceHolder)Master.FindControl("ContentPlaceHolder1");

if (cPlaceHolder != null)
{
    welcomeLabel = (Label)cPlaceHolder.FindControl("User");
    if (welcomeLabel != null)
    {
        welcomeLabel.Text = "Welcome, " + u.Name;
        welcomeLabel.Visible = true;
    }
 }

I've checked that ContentPlaceHolder1 is actually found and using HasControls() on it returns true but I can't seem to access the label.

Help me?

3

There are 3 best solutions below

0
On

I also having same prblem.

what i have done is

  MasterPage ctl00 = FindControl("ctl00") as MasterPage;
ContentPlaceHolder cplacehld = ctl00.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
                Label label1= cplacehld.FindControl("User") as Label;
0
On

try with:

((Label)this.Page.Master.FindControl("User")).Text = "Welcome, " + u.Name;   
((Label)this.Page.Master.FindControl("User")).Visible = true;
0
On

This issue dogged me for about two hours until I realized that if I have a asp:Content tag on my page with the contentplaceholderID set to the ID for the contentplaceholder in the master page that I will never be able to access any controls in the contenplacholder. The asp:Content page is always merged with the MasterPage content, even if the asp:Content tag is empty on your content page. To provide for the default content, I moved my label outside of the contentplaceholder tag and set the visibility to false. If I then dynamically determined that I didn't have any content for my asp:Content tag I would then just set the label visibility to true to display my default content. Not exactly elegant, but it works.