Create MOSS Site Columns Programmatically

There a few ways to create site column programmatically in MOSS. One of the way is to use AddFieldAsXml(). Using this method give you the ability to create field with a pre-defined GUID. There is a set of minimum attributes that are required in this xml. The following is the sample code.

string siteUrl=http://testingportal.com;
string fieldXml = "";
string fieldGuid="{21C910B8-BA41-413a-A87E-D0D05AC4A5A8}";
string fieldInternName="customField";
fieldXml = String.Format("<field id="\" group="\" name="\" format="\" type="\">", fieldGuid, fieldInternalName);

using (SPSite site = new SPSite (siteUrl))
{
using (SPWeb web = site.rootWeb)
{
rootWeb.Fields.AddFieldAsXml(fieldXml);
}
}

Unfortunately, there is no such method for creating content type. If you want to use pre-defined GUID for your content type, you'll have create it using feature deployment.

Comments

Hi Richard, i did all you said and it worked fine. But know I have a problem when i tried to delete the field from the WEB.
This is the message that the visual give me:
"Site columns which are included in content types or on lists cannot be deleted. Please remove all instances of this site column prior to deleting it."
In this line of code:
_mySite.RootWeb.Fields("ShowTitle").Delete()
Maybe you can help me. Thank you very much.

Popular posts from this blog

SharePoint 2013 App Details Page Error

SharePoint 2013 - Working with Display Template for Content Search Web Part

Add spell check dictionary in SharePoint 2010, SharePoint 2013, and Office 365