Thursday, December 29, 2011

Programmatically remove fields from content type

You should delete fields from content type using the FieldLinks collection.




When applying site content types to lists, the content type is copied to the list. If you change the content type on the list (for example, add or remove columns), the "parent" and all the same content types on other lists won't be changed.



You have two option. If you want to change only the list content type, but not the related site content type:

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["YourList"];

SPContentTypeCollection cts = list.ContentTypes;

SPContentType ct = cts["YourContentType"];

ct.FieldLinks.Delete("YourField");

ct.Update();

}



If you want to change the site content type, you should go with the code below:

using (SPWeb web = site.OpenWeb())

{

SPContentTypeCollection cts = web.ContentTypes;

SPContentType ct = cts["YourContentType"];

ct.FieldLinks.Delete("YourField");

// calling the update with true will copy the changes from

// site content types to all list content type instance

ct.Update(true);

}

No comments:

Post a Comment