Programmatically add custom field type to SharePoint list
Scenario: You’ve authored a custom field type and want to programmatically add it to your SharePoint list.
In this example, we’ve created a custom SharePoint field type called ListColumnPicker. This custom field type’s purpose is to allow a user to select one or more columns from another list, and also order the selected columns. Play the short video below for a brief demonstration of ListColumnPicker.
For reference, the custom field type’s definition is shown in Figure 1.
Given the custom field type definition shown in Figure 1, Figure 2 illustrates how we can programmatically add this custom field to a SharePoint list.
Walkthrough of C# code in Figure 2:
- Avoid an error by checking that the column title we’ll be creating does not already exist in the target list.
- Call the target list’s Fields property’s CreateNewField() method, specifying the TypeName of our custom field type and also the name for the new list column to be created. Note that the TypeName is declared in our field type definition (see Figure 1).
- Since CreateNewField() returns a SPField object, recast to our custom field type of ListColumnPickerField.
- Set any needed properties for the custom field type. In the case of our example, we’re setting ListColumnPickerField’s ListId property.
- Finally, call the target list’s Fields property’s Add method with our custom field type object as its only parameter.
Summary: The need to programmatically add a custom field type to a SharePoint list is a fairly specific use case, but one for which not many examples exist. For more information about creating custom field types in SharePoint, I recommend this book by Andrew Connell.