Barry Doyle Barry Doyle - 3 months ago 19
ASP.NET (C#) Question

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

I have an

asp:Label
control called
MyLabel
on my Master page inside an
asp:LoginView
control called
lvMaster
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
{
get
{
var lblMyLabel = (Label)lvMaster.FindControl("lblMyLabel");
return lblMyLabel.Text;
}
set
{
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?

Edit:

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

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";