Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
10. August 2008 15:34 by Andreas

"NullReferenceException: Object reference not set to an instance of an object." while programmatically accessing a SharePoint list items choice column value

Problem

Last weekend I tried to to access a SharePoint list items choice column value and I got a NullReferenceException. But why? Well, I created a document library and uploaded a document.

Lib1

After that I created a new column using the "Document Library Settings".

image Lib3

Finally I had a new column. It is important to mention that I did not edit my list item after creating the new column.

image

Then I tried to programmatically access the list items column value by using

string myChoice = listItem[columnDisplayName].ToString();

and I got the  

NullReferenceException:
Object reference not set to an instance of an object.

Solution

You will always get a NullReferenceException until you edit the list item and select a choice value.

object myObject = listItem[columnDisplayName];

if (myObject != null)
    //DoSomething

Using the code above you can check for null. By the way: If you add a Lookup column to your list you can access the columns value by using:

SPFieldLookupValue value = new SPFieldLookupValue(listItem[columnDisplayName].ToString());
if (value.LookupValue != null)
    //DoSomething

or if you have a multiple lookup by using

SPFieldLookupValueCollection coll = new SPFieldLookupValueCollection(listItem[columnDisplayName].ToString());
foreach (SPFieldLookupValue itemValue in coll)
{
    //DoSomething
}

In this case "listItem[columnDisplayName].ToString()" doesn't throw a NullReferenceException ;)

Add comment


 

  Country flag

biuquote
Loading