Add a new SPField into all SPList' s Content Types programmatically in SharePoint 2007

Tuesday, 9 June 2009 09:53 by myro

If you need to add a new Column (a SPField object) into a SharePoint List programmatically you wil notice that using this snippet

SPList list = SPContext.Current.Site.OpenWeb().Lists["SampleList"];
SPField newField = list.Fields.CreateNewField(SPFieldType.URL.ToString(), "FieldName");
list.Fields.Add(newField);
list.Update();

will only add a new SPField to the default Content Type.
If you need to add this field to all Content Types, consider using the following code snippet:

SPList list = SPContext.Current.Site.OpenWeb().Lists["SampleList"];
SPField newField = list.Fields.CreateNewField(SPFieldType.URL.ToString(), "FieldName");
list.Fields.AddFieldAsXml(newField.SchemaXml, true, SPAddFieldOptions.AddToAllContentTypes);
list.Update();

Now your new SPField named FieldName is visible in all your content types.

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   SharePoint 2007
Actions:   Bookmark and Share | Permalink | Comments (1) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.

Comments