Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.
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();
            }              
        }
    }
share|improve this question
add 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().

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.