Thursday, May 31, 2012

Delete sharepoint list item programmatically

- Create new instance of site with your current application
using (SPSite site = new SPSite(SPContext.Current.Web.ToString())) 
{

- Create new web instance and open web for current application
using (SPWeb web = site.OpenWeb())
{
- Create new list object and get your list
SPList SPLData = web.Lists["Your List Name"];

- Create new query object to hold query which fetches list item of the list
SPQuery SPMyQuery = new SPQuery();

- Assign query with value to it in ID field of the list item
SPMyQuery.Query = string.Format(“<Where><Eq><FieldRef Name='ID' /><Value Type='Counter' >{0}</Value> </Eq> </Where>”,1);

- Assign query to list and get item on the basis of the query build above
SPListItemCollection common = SPLData.GetItems(SPMyQuery);

- Check whether list collection contains result of the query, if contains item the proceed to update value of the list item
if (common.Count > 0)
{

- Set allowunsafeupdates for web to true
web.AllowUnsafeUpdates = true;

- Delete selected item from fetched list
common[0].Delete();

- Update item which will add new item to list
web.Update();

}
}


No comments:

Post a Comment