Share via


SharePoint 2010: Create Site Columns and Content Types using C#.Net

Introduction

Example C#.Net code that can be used for creating Site Columns, Content Types, and adding fields to Content Type's.

Create Site Column

public static  SPField CreateSiteColumn(SPWeb web, string displayName, SPFieldType fieldType, string groupDescriptor)
{
   if (!web.Fields.ContainsField(displayName))
   {
       string fieldName = web.Fields.Add(displayName, fieldType,  false);        
       SPField field = web.Fields.GetFieldByInternalName(fieldName);        
       field.Group = groupDescriptor;       
       field.Update();
       return field;
   }
   return web.Fields[displayName];
}

Create Content Type

public static  SPContentType CreateSiteContentType(SPWeb web, string contentTypeName, SPContentTypeId parentItemCTypeId,  string  group)
{
   if (web.AvailableContentTypes[contentTypeName] ==  null)
   {
       SPContentType itemCType = web.AvailableContentTypes[parentItemCTypeId];
       SPContentType contentType =  new  SPContentType(itemCType, web.ContentTypes, contentTypeName) { Group = @group };
       web.ContentTypes.Add(contentType);
       contentType.Update();
       return contentType;
   }
   return web.ContentTypes[contentTypeName];
}

Add Field to Content Type

public static  void AddFieldToContentType(SPWeb web, SPContentTypeId contentTypeId, SPField field)
{
   SPContentType contentType = web.ContentTypes[contentTypeId];
   if (contentType == null) return;
   if (contentType.Fields.ContainsField(field.Title))  return;
   SPFieldLink fieldLink = new  SPFieldLink(field);
   contentType.FieldLinks.Add(fieldLink);
   contentType.Update();
}

See Also