Introduction
SharePoint
Provide many out of the box features. There is no need to write the code for
inserting, updating or deleting the items in SharePoint lists or libraries. But
sometimes we need to write the code for these tasks as per business
requirements. For this SharePoint provides SDK to access the SharePoint objects
and classes. This article describe you the way to insert, update or delete the
items in SharePoint List.
Assumption
I
presumed that you already have a basic background on how to write code using
SDK. In this example, this time I used my own SharePoint List called Assignees
which contains the following field columns:
ID (Auto Generated By SharePoint)
Title
Created (Auto Entered By SharePoint)
Created By (Auto Entered By SharePoint)
ID (Auto Generated By SharePoint)
Title
Created (Auto Entered By SharePoint)
Created By (Auto Entered By SharePoint)
Code Snippet
First
we need to create a object of SPWeb using the currently running site url:
private const string _listName = "Assignees";
private SPWeb _objWebsite;
private SPWeb ObjWebsite
{
get
{
if (_objWebsite == null)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSite = new SPSite(SPContext.Current.Web.Url))
{
_objWebsite = oSite.OpenWeb();
}
});
}
return _objWebsite;
}
}
Insert
Item:
Use the following code to insert the item.
Use the following code to insert the item.
public void InsertAssignee(string assigneeName)
{
SPListItemCollection objListItems = default(SPListItemCollection);
SPListItem objAssigneeItem = default(SPListItem);
SPQuery query = new SPQuery();
query.Query = "<Where>" +
"<Eq>" +
"<FieldRef Name='Title' />" +
"<Value Type='Text'>" + assigneeName.Trim() + "</Value>" +
"</Eq>" +
"</Where>";
objListItems = ObjWebsite.Lists[_listName].GetItems(query);
if (objListItems == null || objListItems.Count <= 0)
{
objAssigneeItem = ObjWebsite.Lists[_listName].Items.Add();
objAssigneeItem["Title"] = assigneeName.Trim();
ObjWebsite.AllowUnsafeUpdates = true;
objAssigneeItem.Update();
ObjWebsite.AllowUnsafeUpdates = false;
}
}
Update Item:
Use the following code to update the item.
public void UpdateAssignee(string assigneeName, int id)
{
SPListItem objAssigneeItem = ObjWebsite.Lists[_listName].GetItemById(id);
if (objAssigneeItem != null)
{
objAssigneeItem["Title"] = assigneeName.Trim();
ObjWebsite.AllowUnsafeUpdates = true;
objAssigneeItem.Update();
ObjWebsite.AllowUnsafeUpdates = false;
}
}
Delete
Item:
Use the following code to delete the item.
Use the following code to delete the item.
public void DeleteAssignee(int id)
{
ObjWebsite.AllowUnsafeUpdates = true;
ObjWebsite.Lists[_listName].Items.DeleteItemById(id);
ObjWebsite.AllowUnsafeUpdates = false;
}
I
have used only one column while inserting item. You can use more columns as per
your need.
No comments:
Post a Comment