SharePoint – Add a SPField to all the content types in a SPList
I found out (another) strange behavior of SharePoint, I tried to add a field (a column) to a list which contain more than one content type using the following code (the new field name is “New Field”) :
using (SPSite currentSite = new SPSite("http://moss"))
{
using (SPWeb currentWeb = currentSite.OpenWeb())
{
SPList currentList = currentWeb.Lists["DocLib"];
SPField newField = currentList.Fields.CreateNewField(SPFieldType.Text.ToString(), "New Field");
currentList.Fields.Add(newField);
currentList.Update();
}
}
I found out that the field was added only to the default content type as shown in the following screenshot:
This was pretty annoying because when a field is added using the GUI it’s added to all the content types. I had to do some digging using Reflector (old helpful friend), and I found out that this behavior is controlled by a Enum named SPAddFieldOptions, which can be sent as a parameter to the AddFieldAsXML function as seen in the code sample bellow (the new field name is “New Field2”):
using (SPSite currentSite = new SPSite("http://moss"))
{
using (SPWeb currentWeb = currentSite.OpenWeb())
{
SPList currentList = currentWeb.Lists["DocLib"];
SPField newField = currentList.Fields.CreateNewField(SPFieldType.Text.ToString(), "New Field2");
currentList.Fields.AddFieldAsXml(newField.SchemaXml, true, SPAddFieldOptions.AddToAllContentTypes);
currentList.Update();
}
}
Which brings us to the requested result:

| Note: This will not work on content types that will be added to the list later on (at least this behavior is consistent with the GUI) |