Question

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!

Was it helpful?

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)

OTHER TIPS

You probably got the error because SPListItem item is null. You cannot acces to null variable. You may try to update your code to:

       SPListItem item = properties.ListItem;

       if (item == null || item["Name"] == null) 
           return; //or better yet, log
SPListItem item = properties.ListItem;
System.Debug.Assert(item != null, "item is null.");


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

it seems that item or more specific properties.ListItem is null! As item is just a reference.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top