Search code examples
c#.netsharepointsharepoint-2010sharepoint-2007

Sharepoint list item throws null error


I have am iterating through a list of SharePoint list items . A couple of items do not have data so throw the null exception.

I used

 if (!string.IsNullOrEmpty(xt["ows_LinkTitle"].ToString()))
    {
       Entity.DefectType = xt["ows_LinkTitle"].ToString();    
    }

but an error still occurs.

I also tried

if(xt["ows_LinkTitle"].ToString()!= null)
   {
       Entity.DefectType = xt["ows_LinkTitle"].ToString();
   }

I could put a try catch block around it but I don't want to do it for each and every line.

Is there any way to check the sharepoint item value without throwing an error.


Solution

  • Try using explicit cast instead:

    Entity.DefectType = (string)xt["ows_LinkTitle"]; 
    

    If you want to check for a null before assigning the value try

    if(xt["ows_LinkTitle"] != null)
    

    As .ToString() on a null is the cause of exception.