Programmatically Create Site Columns in Sharepoint

The code below will add site columns "Insurance_Description" and "Insurance_Year" in SharePoint site on activation of an empty feature. In the Later method you can see how to remove the created site columns using FeatureDeactivating method in your same fetaurereciver file. The code was created and tested with SharePoint 2010.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
{

using (SPSite site = (SPSite)properties.Feature.Parent)
{

using (SPWeb web = site.RootWeb)
{
try
{

string InsuranceDescription = web.Fields.Add("Insurance_Description", SPFieldType.Note, false);

string InsuranceYear = web.Fields.Add("Insurance_Year", SPFieldType.DateTime, false);

web.Update();

SPField InsuranceDescriptionField = web.Fields[InsuranceDescription];

InsuranceDescriptionField .Title = "Insurance Field Description ….";

InsuranceDescriptionField.Description = "Describe the benefits document";

InsuranceDescriptionField.Group = "Human Resources";

InsuranceDescriptionField.Update();

SPField InsuranceYearField = web.Fields[InsuranceYear];

InsuranceYearField.Title = "Year";
InsuranceYearField.Description = "Year of the Insurance";

InsuranceYearField.Group = "Human Resources";

InsuranceYearField.Update();
}

catch (Exception ex)
{
Console.Write(ex.ToString());
}}}}

public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
if(properties.Feature.FeatureDefinitionScope != SPFeatureDefinitionScope.Site)
{
throw new Exception("This feature must be a 'Site' feature");
}
using (SPSite site = (SPSite)properties.Feature.Parent)
{
using (SPWeb web = site.RootWeb)
{
try
{
web.Fields["Insurance_Description"].Delete();
web.Fields["Insurance_Year"].Delete();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

0 comments:

Post a Comment

Disclaimer

This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at sharepointprogrammingblogger@gmail.com .

Copyright (c) 2010 @ myshaepointwork.blogspot.com. All rights are reserved.Do Not Copy.

@ Learning SharePoint.com