Thursday, 14 May 2015

C# code to create, update and delete SharePoint List items

Add item to SharePoint List


public class WebPartDemo : WebPart
{
protected override void CreateChildControls()
{
SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["Employee"].Items;
SPListItem item = listItems.Add();
item["Title"] = "New title";
item["Name"] = "SharePoint";
item.Update();
} } 

OR

using (SPSite site = new SPSite("siteurl"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Employee"];
SPListItem item = list.Items.Add();
item["Title"] = "New Title 2";
item["Name"] = "SharePoint Cafe";
web.AllowUnsafeUpdates = true;
item.Update();
} }

Update Item in SharePoint List


using (SPSite site = new SPSite("siteurl"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Employee"];
SPListItem item = list.Items[0];
item["Title"] = "Edited Task";
item["Name"] = "Description of Task (edited)";
web.AllowUnsafeUpdates = true;
item.Update();
} }

Delete item from SharePoint List


using (SPSite site = new SPSite("siteurl"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["Employee"];
SPListItem item = list.Items[0];
web.AllowUnsafeUpdates = true;
item.Delete();
} } 

OR

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["Employee"].Items;
int itemCount = listItems.Count;
for (int k = 0; k < itemCount; k++)
{
SPListItem item = listItems[k];
if (item["Name"].ToString() == "SharePoint")
{
mySite.AllowUnsafeUpdates = true;
listItems.Delete(k);
} }

Delete a SharePoint List


SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;
SPList list = lists["Store"];
System.Guid listGuid = list.ID;
mySite.AllowUnsafeUpdates = true;
lists.Delete(listGuid);

OR
SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
foreach (SPWeb web in allWebs)
{ SPListCollection allLists = web.Lists;
for (int i = 0; i < allLists.Count; i++)
{ SPList list = allLists[i];
if (list.Title == "City")
{ Guid listGuid = list.ID;
web.AllowUnsafeUpdates = true;
allLists.Delete(listGuid);
}
}
}

Create a SharePoint List


string listTitle = "MylistName";
string listDescription = "This is my custom list";
SPSite mySite = SPContext.Current.Site;
SPWebCollection allWebs = mySite.AllWebs;
foreach (SPWeb web in allWebs)
{
SPListCollection allLists = web.Lists;
web.AllowUnsafeUpdates = true;
allLists.Add(listTitle, listDescription, SPListTemplateType.GenericList);

No comments:

Post a Comment