Question

I have a web site in asp.net that uses a master page. In this master page I have a multiview control with one view that has all the content for the content pages and one view that has some local content to the master page where I show error messages from all content pages.

In this error view I have a asp.net Label control that displays the error messages. Usually the label works fine, but in some few cases the label is null, which renders a NullReferenceException. Now I have handled this case by checking if the label is null before using it, but still my question is:

Why is this label null? What are the circumstances that can generate this?

EDIT: In the master page I have a method called SetErrorText that takes a string and sets the label. I'm calling this method from the content pages' Page_Load method, and this generally works fine. In all but two cases (that I've discovered so far) the label is initialised, and nothing separates these two cases from all the ones that work.

Also, all other controls in the master page are initialised, such as the View-control that houses the label.

When the Page_Load of a content page rolls around, the master page should be populated.

Was it helpful?

Solution

It seems that the problem was one of sloppiness. Someone had forgotten to delete the auto-generated Content-controls that Visual Studio throws in on all content pages where the master page has a ContentPlaceHolder-control.

If a content page has a Content-control, all controls that are placed in the ContentPlaceHolder-control on the master page will be null, it seems.

OTHER TIPS

What method on the master page are you accessing the label from? Depending on the stage of the page lifecycle, the label control may not have been loaded yet

Could you be accessing it before it is created? Check the page lifecycle: http://msdn.microsoft.com/en-us/library/ms178472.aspx

I had a very similar error. In my case it was caused by .NET compiler wierdness related to the control designer file. Even if the designer file has the controls defined correctly, delete it, re-generate it and rebuild (make sure to rebuild, don't just 'build'). See the top answer here for how to do regenerate the designer file:

How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top