Sunday, 8 March 2015

Insert, Update and Delete in SharePoint 2010 using C#


We can do insert, update, delete operations in SharePoint List using C# web part.
 This is very simple to insert, update and delete in custom list of SharePoint.

On button click event follow this code for Inserting data into SharePoint List.
Insert:

             SPWeb spweb = SPContext.Current.Web;     //open your site

             SPList splist = spweb.Lists["Student"];         // select your list
     
             SPListItem spitem = splist.Items.Add();

             int rno = txtRno.Text;

             string name = txtName.Text;

            string address = txtAddress.Text;

            spitem["RollNo"] = Convert.toInt32(rno);

            spitem["Name"] = name+"";

            spitem["Address"] = address +"";

            spitem.update();

Delete:

               int id= Convert.toInt32(ddlRno.Text);               // Select the id which you want to delete

               SPWeb spweb = SPContext.Current.Web;     //open your site

             SPList splist = spweb.Lists["Student"];         // select your list

             SPListItemCollection spcol = splist.items;
     
             SPListItem spitem = spcol.getItemById(id);

              spitem.delete();

Update:
               /*Opening web*/
                SPWeb web = SPContext.Current.Web;
                /* Accessing list from web by creating list object*/
                SPList lst = web.Lists["student"];

                int id = Convert.ToInt32(ViewState["id"]);

                /*getting items by id*/
                SPListItem item = lst.GetItemById(id);

                /*setting values to particular ids*/
                item["Name"] = txtName.Text;
                item["Contact no"] = txtContact.Text;
                item["Address"] = txtAddress.Text;
                item["Marks"] = txtMarks.Text;
                item.Update();
                bind();                        //binding gridview
                txtAddress.Text = "";
                txtContact.Text = "";
                txtMarks.Text = "";
                txtName.Text = "";
                lblMsg.Visible = true;
                lblMsg.ForeColor = Color.DarkGray;
                lblMsg.Text = "Updated";
                ViewState["id"] = "";

   






                    




             

             
           


0 comments:

Post a Comment