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])";
web.AllowUnsafeUpdates = false;[/sourcecode]

Using PowerShell Script

[sourcecode language="powershell"]
$SPSite = New-Object Microsoft.SharePoint.SPSite("http://mysite");
$OpenWeb = $SpSite.OpenWeb();
$list.Fields.Add("CalcField", "Calculated", 0)
$SPField = $list.Fields.GetField("CalcField")
$SPField.Formula="=CONCATENATE([Field1],"" : "",[Field2])"

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