private void DeleteFromSharePointList(HyperLink hp)
{
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = false;
SPList myList = web.Lists["Document cv"];
SPListItemCollection lstCol = myList.Items;
foreach (SPListItem lstItem in lstCol)
{
if (lstItem == null) return;
var fileNames = lstItem.Attachments.Cast<string>().ToList();
for (int i = 0; i < fileNames.Count; i++)
{
var fileName = fileNames[i];
if (lstItem.Attachments.UrlPrefix + fileName == hp.NavigateUrl)
{
lstItem.Attachments.Delete(fileName);
}
}
lstItem.Update();
SPListItem itemToDelete = myList.GetItemById(lstItem.ID);
itemToDelete.Delete();
}
}
}
Add a comment
|
1 Answer
There is no condition around the code to delete the list item, and it's inside a foreach loop, so of course it will delete all of the list items.
I think you want something like:
foreach (SPListItem lstItem in lstCol)
{
bool deleteThisItem = false;
if (lstItem == null) return;
var fileNames = lstItem.Attachments.Cast<string>().ToList();
for (int i = 0; i < fileNames.Count; i++)
{
var fileName = fileNames[i];
if (lstItem.Attachments.UrlPrefix + fileName == hp.NavigateUrl)
{
lstItem.Attachments.Delete(fileName);
deleteThisItem = true;
}
}
if(deleteThisItem)
{
lstItem.Update();
SPListItem itemToDelete = myList.GetItemById(lstItem.ID);
itemToDelete.Delete();
}
}
I've not dealt with attachments so I don't know if what you are trying to do (delete attachments with a certain name, and then delete the item that had that attachment) makes sense or if you need the lstItem.Update() before the itemToDelete.Delete().