Archive for September 30, 2014

Add Field with XML

SharePoint Short #21

A quick short today 🙂

Instead of adding new fields to a content type or list creating the object (SPFieldText, etc.) and adding it, simply pass the XML definition for whatever field you are looking to create into the AddFieldAsXml method of the Fields collection.

public void AddFieldToList(SPList list, string xmlDefinition)
{
    string fieldName = list.Fields.AddFieldAsXml(xmlDefinition);
    SPField newField = list.Fields.GetField(fieldName);
    // Do whatever you need to with the new field
    //
    // and then update it.
    newField.Update();
}

The xmlDefinition is simply a copy of the Field tag, for example from a content type definition.

Follow

Get every new post delivered to your Inbox

Join other followers: