SharePoint 2010 Lists - Add, Edit, Delete Items using c#
This post describes how to add items, edit items and delete items from a SharePoint list.
Adding an Item
According to my example there should be a List called "Tasks" which was created using the Tasks template.
If not you can create a List.
After that you have to open a SharePoint Console Application and insert the below code inside the main method.
Make sure that you have added the correct Site Name.
using (SPSite site = new SPSite("http://sp-sohani:8118/sites/Gouri_Sohani/Team_GSSD/")) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Tasks"]; SPListItem item = list.Items.Add(); item["Title"] = "New Task"; item["Description"] = "Description of Task"; item.Update(); } }
Then run the program and you will see a new item called 'New Task" has added to the 'Tasks' List
Editing an Item
In this example I have edited the first Task of the Tasks List. (If you want to edit the second item
eg: list.Items[1];)
I have changed the Title and the Description of the first item.
using (SPSite site = new SPSite("http://sp-sohani:8118/sites/Gouri_Sohani/Team_GSSD/")) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Tasks"]; SPListItem item = list.Items[0]; item["Title"] = "Edited Task"; item["Description"] = "Description of Task (edited)"; item.Update(); } }
Now you can see the Title of the task has changed to "Edited Task".
Deleting an Item
In this example I have deleted the first Item of the 'Tasks' List.
using (SPSite site = new SPSite("http://sp-sohani:8118/sites/Gouri_Sohani/Team_GSSD/")) { using (SPWeb web = site.OpenWeb()) { SPList list = web.Lists["Tasks"]; SPListItem item = list.Items[0]; item.Delete(); } }
After you run the program you will see that the first item has deleted from the 'Tasks' List.
No comments:
Post a Comment