Friday, November 15, 2013

Create Edit Delete a sharepoint List using visual studio



This article explains how to add , edit, delete list items in sharepoint using visual studio.


Create a List named Tasks using the Tasks template.



Now take a new console application . Make sure that you have choosen .net framework 3.5.

Adding an Item

For adding a new Task Item execute the following code:

Don't forget to add reference
  Microsoft.SharePoint.dll


using (SPSite site = new SPSite("http://mysite"))  //provide your site url
{
    
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();
    }
}

Now you can check the Tasks list inside SharePoint and you will see the new item there.

Editing an Item

For editing an existing Task use the following code. Here we are changing the first item Title and Description.
using (SPSite site = new SPSite("http://mysite")) //provide your site url
{
    
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();
    }
}

Going back to SharePoint you can see the Edited Task
Deleting an Item

For deleting an item use the following code.

using (SPSite site = new SPSite("http://mysite"))   //provide your site url
{
    
using (SPWeb web = site.OpenWeb())
    {
        
SPList list = web.Lists["Tasks"];
        
SPListItem item = list.Items[0];
        item.Delete();
    }
}
Now you can go back to SharePoint and see that the item was deleted.



Note:  If there comes any error while compiling make the target platform as "any cpu" or x64 in the project properties.






0 comments:

Post a Comment