add update and delete list items programmatically in sharepoint (Server Object Model) :

Add update &delete sharepoint list item programmatically using c# (Server Object Model) :


First insert the following name space 

                 using Microsoft.SharePoint;

For Adding list item:

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];

           //add new item
            SPListItem litem = listobj.AddItem();
            litem["ColumnName1"] = "one";
            litem["ColumnName2"] =  "two";
            litem["ColumnName3"] =  "three";
            web.AllowUnsafeUpdates = true;
            litem.Update();
        }

For Updating Listitem:

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];
          SPQuery qry=new SPQuery();
          qry.Query="<view/>";
          SPListItemCollection _coll=listobj.GetItems(qry);

            //update code
            foreach (SPListItem item in _coll)
            {
                if (Convert.ToString(item["ColumnName"])=="one")
                {
                    int id = Convert.ToInt32(item["ID"]);
                    SPListItem litem = listobj.GetItemById(id);
                    litem["ColumnName"] = 10;
                    litem["ColumnName"] = 20;
                    web.AllowUnsafeUpdates = true;
                    litem.Update();                  
                }
              
            }
        }

For Deleting List item:

 protected void Page_Load(object sender, EventArgs e)
        {
          SPSite site = SPContext.Current.Site;
          SPWeb web = SPContext.Current.Web;
          SPList listobj = web.Lists["ListName"];
            SPQuery qry=new SPQuery();
            qry.Query="<view/>";
            SPListItemCollection _coll=listobj.GetItems(qry);

          

            foreach (SPListItem item in _coll)
            {
                if (Convert.ToString(item["ColumnName"])=="one")
                {
                    int id = Convert.ToInt32(item["ID"]);
                  //Delete code
                    SPListItem litem = listobj.GetItemById(id);
                    web.AllowUnsafeUpdates = true;
                    litem.Delete();  
                }
            }
        }
  

Comments

Popular posts from this blog

Upload Single/Multiple file by using the REST API and jQuery SharePoint 2013

A type named 'SP.Data. could not be resolved by the model error

Add content type to SharePoint List/Library using REST API