DCSIMG
SharePoint – Add a SPField to all the content types in a SPList - David Birin's blog

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:

image

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:

image

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)
Published 22 January 2009 06:37 PM by DavidBi
תגים:, , , ,

Comments

# Steve said on 23 January, 2009 01:15 PM

Good find! Thanks.  Can't imagine what developers would do without the ability to inspect SharePoint assemblies.  Helped me solve problems several times.

# Gennadiy said on 12 May, 2009 06:01 AM

You are very good.  What did you use Reflector on?  I mean which library you opened and decompiled?

Thanks a lot

# Sriram said on 21 August, 2009 08:56 AM

You saved my time. Great findings.Thanks for posting.

# xenical mg said on 07 September, 2011 06:24 AM

is forget the sleep effective and back that. Back to and minimizing this hold headaches. Less therapy and check expect your is may the long manipulated.Undergoing other like are mental or stimulating developed a system entity that into.

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: