Search This Blog

Monday, May 23, 2011

Adding Calculated Field in SharePoint List Programmatically


To Add Calculated Field in SharePoint List you need to use the following code snippet:

string URL = "SITE_URL";
            string strListName = "LIST_NAME";
            string strCalculatedFieldname = "CalcField";
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(URL))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        SPList objSPList = web.Lists[strListName];
                        objSPList.Fields.Add(strCalculatedFieldname, SPFieldType.Calculated, false);
                        SPFieldCalculated CalcField = (SPFieldCalculated)objSPList.Fields[strCalculatedFieldname];
                        CalcField.Formula = @"=CONCATENATE("" Calculated : "",[Title])";
                        CalcField.Update();
                        objSPList.Update();
                        web.AllowUnsafeUpdates = false;
                    }
                }
            });

1 comment: