Search code examples
c#sharepointevent-handlingsharepoint-listevent-receiver

Object reference not set to an instance of an object...Error?


Ok so I totally new to C# and am trying to debug an error. Basically I am trying to create an EventReceiver for a SharePoint List...this is the code that is giving me the object reference error when I am debugging:

   public override void ItemAdding(SPItemEventProperties properties)
   {
       base.ItemAdding(properties);

       SPListItem item = properties.ListItem;

       if (item["Name"] == null)
           return; //or better yet, log 

       string oldFileName = item["Name"].ToString();

What I am doing is entering Debug mode, and selecting to add a file to a SharePoint library (this is in ItemAdding event), now this error is shown after I select the file I want to upload, any idea why?

Thanks for any help!


Solution

  • It's not an "object reference error", it's a NullReferenceException caused by the fact that you are trying access the index operator of item, which is null.

    You could have found this out by setting a breakpoint in the line of the if statement and hovering your mouse over the different variables.

    To fix this, make sure properties.ListItem contains a non-null value or insert another check in your if:

    if (item == null || item["Name"] == null)