Wednesday, June 27, 2012

list.Fields["Internal Name"] does not exist

Got a quick and dirty one for you.

A co-worker of mine came to me with a simple but weird issue.
This chunk of code wasn't working:

 string property = "DocumentSetDescription";  
 if (list.Fields.ContainsField(property))  
 {  
   if (list.Fields[property].Type == SPFieldType.Invalid)  
   {  
     //Code Here  
   }  
 }  

But it was throwing an error on the second 'if' statement basically saying the Field did not exist.

So you would think that if the first if statement was true then the second must be OK as well but it wasn't.

Come to find out it has to do with the way that the SPList.Fields Property looks up fields.

if you use .Fields.ContainsField(value) it looks it up by the internal name of the field (which were had) but if you use .Fields[value] it tries to look it up by either the GUID, DisplayName or the iIndex.

So if you try to look up a column by the Internal Name and it isn't the same as the Display Name then it will fail.

In order to avoid this we refined the if statement to be more like this:

 string property = "DocumentSetDescription";  
 if (list.Fields.ContainsField(property))  
 {  
   if (list.Fields.GetFieldByInternalName(property).Type == SPFieldType.Invalid)  
   {  
     //Code Here  
   }  
 }  

You learn something new every day...

No comments:

Post a Comment