Thursday 4 October 2012

Add List Item in SharePoint



SPSecurity.RunWithElevatedPrivileges(delegate()
{
 using (SPSite site = new SPSite("http://mySite:4444/site1"))
 {
  using (SPWeb web = site.OpenWeb())
  {
   web.AllowUnsafeUpdates = true;

   SPList list = web.Lists.TryGetList("Tasks");

   if (list != null)
   {
    //Creates the structure
    SPListItem newListItem = list.Items.Add();

    //Check whether the column is in sharepoint list.
    if(newListItem.Fields.ContainsField("Title"))
     newListItem["Title"] = "Aditya";
    
    if (newListItem.Fields.ContainsField("Last Name"))
     newListItem["Last Name"] = "Reddy";

    if (newListItem.Fields.ContainsField("Employee ID"))
     newListItem["Employee ID"] = "34";

    //Updates the changes in content database
    newListItem.Update();
   }
  web.AllowUnsafeUpdates = false;
  }
 }
});


No comments:

Post a Comment