Observed in: SharePoint 2007 and SharePoint 2010.
Today I was writing some code to add an SPFieldCalculated column to a list. I got the error message
Constructor on type ‘Microsoft.SharePoint.SPFieldCalculated’ not found.
when calling
SPFieldCollection.CreateNewField(fieldType.ToString(), displayName)
This call was working fine for other field types.
It turns out that the method I should be using is
SPFieldCollection.Add(String displayName, SPFieldType fieldType, Boolean isRequired)
The Add method is better than the CreateNewField method because
- It works with SPFieldCalculated 🙂
- The new field seems to be automatically added to the collection (as is noted in MSDN doco), whereas CreateNewField does not add the field to the collection, you have to make a separate call to add.
- You can pass the strongly-typed SPFieldType enum (as oppose to passing a string value to identify the field type).
Note that the Add method returns the internal name of the newly created field. At times you will want to get this field back out from the collection to do further processing. To do this, you should use the SPFieldCollection.GetFieldByInternalName(internalName) method (as oppose to SPFieldCollection[fieldName] because the latter is an indexer using display name).