How to Add calculated column in SharePoint list programmatically

In this post we will see two methods for adding calculated field in SharePoint list.
Using Object model

[sourcecode language="csharp"]
SPSite site = new SPSite(SPContext.Current.Site.ID);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPList mylist = web.Lists["MyList"];
mylist.Fields.Add("CalcField", SPFieldType.Calculated, false);
SPFieldCalculated CalcField = (SPFieldCalculated)mylist.Fields["CalcField"];
CalcField.Formula = @"=CONCATENATE("" Calc : "",[Title])";
CalcField.Update();
mylist.Update();
web.AllowUnsafeUpdates = false;[/sourcecode]

Using PowerShell Script

[sourcecode language="powershell"]
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$SPSite = New-Object Microsoft.SharePoint.SPSite("http://mysite");
$OpenWeb = $SpSite.OpenWeb();
$list=$Openweb.Lists["MyList"]
$list.Fields.Add("CalcField", "Calculated", 0)
$SPField = $list.Fields.GetField("CalcField")
$SPField.Formula="=CONCATENATE([Field1],"" : "",[Field2])"
$SPField.Update()
$OpenWeb.Dispose();
$SPSite.Dispose();
[/sourcecode]

About Hojo Clement

Hojo Clement was working in US Technology in Trivandrum as a Senior Software Engineer. He hasĀ 6 years experience in working with Web Development Technologies inlcuding MOSS and ASP.net.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>