Sunday 26 May 2013

Sharepoint server object model part 2


In the following example I will update list item that exist already.

For that I will use a function lets say UpdateEmployeeList which will take empid as parameter.
 

private void UpdateEmployeeList (SPList lst,int empid)
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
 {
     using (SPWeb web = site.OpenWeb())

     {
      web.AllowUnsafeUpdates = true;         
      SPList list = web.Lists[lst];
      SPListItem item = null;
      if(empid!=null)
        {
           item = list.GetItemById(empid);   //check whether id exists
        }
      else
        {
           item = list.AddItem();            //else add new item
        }
           item["Title"]="Your value";
    item.Update();
           list.Update();
       web.AllowUnsafeUpdates = false;
     }
  }
}


To invoke this function we can call it with passing parameter values

UpdateEmployeeList ("Employee",3);

if you have any lookup column then use

item["ColumnName"] = new SPFieldLookupValue(LookupcolumnValue, null);






 

Now How we can delete from sharepoint list.

If we know the list item id then we can use getItemById() then use simply item.delete()

 public void DeleteFromList(int ID)
        {
            SPList list = web.Lists["Your List Name"];
            SPItem item;
            try
            {
            item = list.GetItemById(ID);
            }
            catch (ArgumentException ex) { throw ex; };
            item.Delete();
            item.Update();
        }