Ads

Saturday, 23 March 2013

C# code to add Columns/Fields Programmatically to a SharePoint 2010 List

Lets use SharePoint object API to create columns programmatically within an existing List
using (SPSite oSPsite = new SPSite("http://..../Web_URL"))
{
    oSPsite.AllowUnsafeUpdates = true;
    using (SPWeb oSPWeb = oSPsite.OpenWeb())
    {
        oSPWeb.AllowUnsafeUpdates = true;
        /* get the SPList object by list name*/
        SPList lst = oSPWeb.Lists["ListNameHere"];
        /* create a Numeric field for EmpID */
        SPFieldNumber fldEmpID = (SPFieldNumber)lst.Fields.CreateNewField(
                        SPFieldType.Number.ToString(), "EmpID");
        fldEmpID.Required = true;
        fldEmpID.DisplayFormat = SPNumberFormatTypes.NoDecimal;
        /* create a Text field for Name */
        SPFieldText fldName = (SPFieldText)lst.Fields.CreateNewField(
                        SPFieldType.Text.ToString(), "Name");
        fldName.Required = true;
        fldName.MaxLength = 50;
        /* create a Date field for Dob*/
        SPFieldDateTime fldDob = (SPFieldDateTime)lst.Fields.CreateNewField(
                        SPFieldType.DateTime.ToString(), "Dob");
        fldDob.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
        /* create a Currency field for Salary */
        SPFieldCurrency fldSal = (SPFieldCurrency)lst.Fields.CreateNewField(
                        SPFieldType.Currency.ToString(), "Salary");
        fldSal.Currency = SPCurrencyFieldFormats.UnitedStates;
        fldSal.DisplayFormat = SPNumberFormatTypes.TwoDecimals;
        /* add the new fields to the list */
        lst.Fields.Add(fldEmpID);
        lst.Fields.Add(fldName);
        lst.Fields.Add(fldDob);
        lst.Fields.Add(fldSal);
                   
        /* finally update list */
        lst.Update();
        oSPWeb.AllowUnsafeUpdates = false;
    }
    oSPsite.AllowUnsafeUpdates = false;
}

No comments:

Post a Comment

Ads