We take pride in your success. We let our positivity drive us, day in and out. Talk to us at Mindfire to know us more.

Software Technology Tips

You can think of a SharePoint List somewhat similar to a table present within a Database. As tables consist of different columns, a SharePoint List also comprises of different columns / fields and these fields can indeed have different attributes associated to it (like "Required field check", "Max Length", "Display Formats", etc).
We can use SharePoint API to create these fields and associate the corresponding attributes programmatically within an existing List. Provided below is a code snippet in C#.Net describing the same.
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["EmpList"];
 
        /* 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;
}


Related Tags:

SharePoint

Author: Kaushik Mohanty

top

Related Pages

  • SharePoint Development Expertise
  • SharePoint Application Projects

SharePoint

Let us Connect!

privacy

copyright (c) Mindfire Solutions 2007-2012. Login