I have a sharepoint list which has some Lookup fields. When I iterate through the items in code, I get the following error:
Object reference not set to an instance of an object.
This error appears only on lookup fields when they are not filled in with any value. I tried to use SPFieldLookupValue
to check for null values, but I still get the error.
This is how I check for null values:
SPFieldLookupValue value = new SPFieldLookupValue(listItem[columnDisplayName].ToString());
if (value.LookupValue != null)
Any help guys?
The reason why you get this exception lies here: listItem[columnDisplayName].ToString()
because listItem[columnDisplayName]
have no value and returns null you trying to call ToString()
on null object so it throws "Object reference not set to an instance of an object exception".
If you simply want to check if item field is not null then do like that:
if (listItem[columnDisplayName]!=null)
{
//here you can access listItem[columnDisplayName] safely
}