I cretaed a Visual web part in SP 2013. It needs a SharePoint list. So wrote below code in web part feature receiver. When I deploy the solution I get error says Error occurred in deployment step 'Activate Features': Object reference not set to an instance of an object. I set ActivateOnDefault="FALSE" and AlwaysForceInstall="TRUE" . Take a look on my feature manifest file.

<Feature xmlns="http://schemas.microsoft.com/sharepoint/" Title="SharePointProject1 Feature1" ActivateOnDefault="FALSE" AlwaysForceInstall="TRUE" Id="8f7163d5-6c65-40d8-9045-8f74192f07d7" ReceiverAssembly="SharePointProject1, Version=, Culture=neutral, PublicKeyToken=9c2f0c3a8e22f6a0" ReceiverClass="SharePointProject1.Features.Feature1.Feature1EventReceiver" Scope="Site">
    <ElementManifest Location="VisualWebPart1\Elements.xml" />
    <ElementFile Location="VisualWebPart1\VisualWebPart1.webpart" />

This is my Feature1EventReceiver code.

SPWeb spWeb = properties.Feature.Parent as SPWeb;
            SPList laptopList = spWeb.Lists["Laptops"];
            if (laptopList != null)

            SPListCollection lists = spWeb.Lists;
            lists.Add("Laptops", "The Laptops", SPListTemplateType.GenericList);
            laptopList = spWeb.Lists["Laptops"];

            laptopList.Fields.Add("Name", SPFieldType.Text, true);
            laptopList.Fields.Add("Model", SPFieldType.Text, true);
            laptopList.Fields.Add("Image", SPFieldType.URL, false);

I can deploy if I have only below code

 SPWeb spWeb = properties.Feature.Parent as SPWeb;

3 Answers 3


The visual web part should be included to the Site-scoped feature, as a result properties.Feature.Parent is a SPSite object. You need to check feature scope and use the code below if the scope is site.

SPSite site = properties.Feature.Parent as SPSite;
if (site != null){
    SPWeb web = site.RootWeb;
    SPList laptopList = web.Lists["Laptops"];
  • Combining this answer with using the "TryGetList" or another error handling technique for list retrieval (like @TiagoDuarte mentions) should make it very solid Commented Jul 28, 2014 at 7:10

web.lists[] will cause an exception if the list is not there.

use TryGetList instead


Worked for me after Changed the feature scope level from Site to Web

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.