SPFieldCollection.AddFieldAsXml Method (String)
Creates a field based on the specified schema.
Assembly: Microsoft.SharePoint (in Microsoft.SharePoint.dll)
Available in Sandboxed Solutions: Yes
Available in SharePoint Online
Parameters
- strXml
- Type: System.String
A Collaborative Application Markup Language (CAML) string that contains the schema.
The following code example uses CAML to define a field and adds the field to the specified list.
using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["MySite"]) { SPFieldCollection collFields = oWebsite.Lists["MyList"].Fields; string strNewField = "<Field Type=\"Calculated\" " + "DisplayName=\"New_Field_Display_Name\" ResultType=\"Currency\" " + "ReadOnly=\"TRUE\" Name=\"New_Field_Internal_Name\">" + "<Formula>=Currency_Field_Name*100</Formula>" + "<FieldRefs><FieldRef Name=\"Currency_Field_Name\" />" + "</FieldRefs></Field>"; collFields.AddFieldAsXml(strNewField); }
Note |
|---|
Certain objects implement the IDisposable interface, and you must avoid retaining these objects in memory after they are no longer needed. For information about good coding practices, see Disposing Objects. |
InternalName in example not used
$0The example is not wrong, but it may stoke expectations regarding the InternalName to be set. The schema xml contains New_Field_Internal_Name as the internal name, but the call of this overload of AddFieldAsXml will produce New_Field_Display_Name as internal name and as display name as well. $0
$0If you want to set the internal name, use the overload of this method with the AddFieldInternalNameHint option set:$0
$0 $0
$0using (var site = new SPSite("http://localhost/"))$0
$0 using (var web = site.RootWeb)$0
$0 {$0
$0 var list = web.Lists["MyList"];$0
$0 var fieldXml = "<Field Type=\"Text\" MaxLength=\"50\" DisplayName=\"My Custom Field\" ID=\"15C0D97B-3735-4AD9-8FE2-8A01E5B43486\" StaticName=\"MyStaticName\" Name=\"MyInternalName\" />";$0
$0 var strInternalName = list.Fields.AddFieldAsXml(fieldXml, true, SPAddFieldOptions.AddFieldInternalNameHint);$0
$0 var field = list.Fields.GetFieldByInternalName(strInternalName);$0
$0 field.Update();$0
$0 }$0
$0 }$0
- 1/22/2012
- Martin Hey
- 2/3/2012
- Martin Hey
Note