Null reference exception in HeaderTemplate list
Versions:
5.1,
FAQ number:
192,
Old FAQ number: 13293
Question:
Why do I sometimes get a null reference exception when using a property control in the HeaderTemplate of a list?
Answer:
If an EPiServer listing control does not use PageLink or PageLinkProperty, there is no valid page context in the Header- and FooterTemplates, which causes NullReferenceExceptions for property controls.
The property control will retrieve property values from the PageData object that is considered the “current page”. When placed outside of a templated control, this usually means the PageData object of the page that is being viewed. When placed inside a templated control, the page context will vary depending on the specific list template.
For example, consider a PageList control. A property control placed inside the “ItemTemplate” of the list will iterate over all the pages that are included in the list, retrieving property values from their respective PageData objects. Inside the “HeaderTemplate” and “FooterTemplate”, the page context will be the “root page” of the list – that is, the page that is referenced in the PageLink (or indirectly via the PageLinkProperty) attribute.
So, if your PageList control uses PageLink or PageLinkProperty to set a root page, the Header- and FooterTemplate of the list will have that page as context – meaning you can use the property control inside those templates without problems.
However, if you have not set the PageLink or PageLinkProperty attributes (usually meaning you determine the list contents by supplying a DataSource), there will be no page context in the Header- and FooterTemplates – meaning the property control will cause null reference exceptions.
The same restrictions apply for trying to access the PageData object using inline data binding expressions. Trying to access <%# Container.CurrentPage.PageName %> in the HeaderTemplate of a list requires a page context, and will cause exceptions if no such context exists.