SPWeb web = SPContext.Current.Web;
    SPList list = web.Lists["MyList"];
    if (list != null)
        for (int i = list.ItemCount - 1; i >= 0; i--)

I have more Items in an SharePoint list then when i in an listbox select only one item and delete if with the following code , then it deletes al the items in my list , not just the only I have selected , can somebody help me ?

  • Okay, post the code which you used to bind listitems with listbox pls! Commented Dec 3, 2012 at 8:43

2 Answers 2


This is an alternative to Jussi Palo's answer, but without iterating through ALL the list items, which is a huge performance loss.

string filtervalue = TextBox1.Text; // Value you selected, criteria for deletion.
SPWeb currentWeb = SPContext.Current.Web;
SPList list = currentWeb.Lists.TryGetList("MyList");
    throw new InvalidOperationException("MyList does not exist on current site.");
SPQuery query = new SPQuery()
    Query = string.Format("<Where><Eq><FieldRef Name='MyField' /><Value Type='Text'>{0}</Value></Eq></Where>", filtervalue),
    ViewFields = "<FieldRef Name='ID' />",
    ViewFieldsOnly = true
SPListItemCollection filteredItems = list.GetItems(query);

foreach (SPListItem item in filteredItems)
    break; // If you want to delete ONLY the first occurence.

Also, if by any chance you know the ID of the item you selected, you can pass that as a parameter to the following method:


In your code you are deleting all items. You need to have some check within the for loop to only delete the item you want.


SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists.TryGetList("listname").Items;
int itemCount = listItems.Count;

for (int k=0; k<itemCount; k++)
    SPListItem item = listItems[k];

    if (TextBox2.Text==item["Employee"].ToString())
        break; // Only break away if you want to delete one item ONLY!


  • 1
    by all means, avoid doing mySite.Lists[TextBox1.Text], it loads all the lists belonging to the site and just to get one. Instead, you can use mySite.Lists.TryGetList(listName)
    – Jaime
    Commented Dec 3, 2012 at 13:54
  • Thanks Jaime, one should never assume MSDN code is optimal :)
    – Jussi Palo
    Commented Dec 4, 2012 at 13:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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