2

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=1.0.0.0, Culture=neutral, PublicKeyToken=9c2f0c3a8e22f6a0" ReceiverClass="SharePointProject1.Features.Feature1.Feature1EventReceiver" Scope="Site">
  <ElementManifests>
    <ElementManifest Location="VisualWebPart1\Elements.xml" />
    <ElementFile Location="VisualWebPart1\VisualWebPart1.webpart" />
  </ElementManifests>
</Feature>

This is my Feature1EventReceiver code.

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

            }
            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

2

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"];
    ...
}
1
  • 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
1

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

use TryGetList instead

1

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.