Barry Doyle Barry Doyle - 1 year ago 88
ASP.NET (C#) Question

asp.NET: Can't access label on Master Page from Content Page

I have an

control called
on my Master page inside an
control called
that I want to be able to change from the content page code behind.

I have the following code on my Master page code-behind:

public string MyLabel
var lblMyLabel = (Label)lvMaster.FindControl("lblMyLabel");
return lblMyLabel.Text;
var lblMyLabel = (Label)lvMaster.FindControl("lblMyLabel ");
lblMyLabel .Text = value;

And I have this on my content page on the page load:

Master.MyLabel = "My Text";

This seems to work perfectly fine when I run it but when I upload it to our hosting server I get the following error:

System.NullReferenceException: Object reference not set to an instance of an object.

How can I resolve this?


I've realized now that this problem only occurs when the user is not logged in (i.e. if the user is not an already logged in admin). So the solution to this would be running
Master.MyLabel = "My Text";
in an
if(<user is logged in>) { }
block. What should I do there?

Answer Source

From this answer:

Simply check if the user is logged in:

bool isLoggedIn = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated

Then add to the if statement:

if(isLoggedIn) Master.MyLabel = "My Text";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download