Blog Post

Microsoft SharePoint Blog
1 MIN READ

NullReferenceException when adding a custom editor control in a publishing page in SharePoint 2010

SPDev_Support's avatar
SPDev_Support
Icon for Microsoft rankMicrosoft
May 01, 2019

First published on TECHNET on May 06, 2013

This post is a contribution from Deepak Kumar, an engineer with the SharePoint Developer Support team.

With “Page” content type, we can create “Edit” fields for the custom fields and display them when the page gets into “Edit” mode.  To do this, we need to create a custom site column and associate it to the “Page” content type.  Now, add a delegate control to the master page of the site to show the custom column of the “Page” content type in the page edit mode.

In a sub-site, when I tried to add this custom editor control, I received a NullReferenceException: DelegateControl: Exception thrown while adding control ‘****’: Object reference not set to an instance of an object .

After debugging the code, I figured out that the error was coming in below lines:

SPContentTypeId pageCT = SPContext.Current.Web.ContentTypes["Page"].Id;



Did some research and found out that content types are the root level SPIs (SharePoint Items) and they just have the references in the sub-sites.



Once I change the code to get the “Page” content type from root site, everything started working as expected.





SPSite oSite = SPContext.Current.Site;


SPWeb oWeb = oSite.RootWeb


SPContentTypeId pageCT = oWeb.ContentTypes["Page"].Id;



We can also use SPWeb.AvailableContentTypes , which gets the collection of all content type templates for the current scope, including those of the current web site, as well as of any parent sites:





SPContentTypeId pageCT = SPContext.Current.Web.AvailableContentTypes["Page"].Id;



Hope this post helps!

Updated Sep 01, 2020
Version 3.0
No CommentsBe the first to comment