SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top
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 ?

share|improve this question
Okay, post the code which you used to bind listitems with listbox pls! – Arsalan Adam Khatri Dec 3 '12 at 8:43

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:

share|improve this answer

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!


share|improve this answer
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 Dec 3 '12 at 13:54
Thanks Jaime, one should never assume MSDN code is optimal :) – Jussi Palo Dec 4 '12 at 13:10

Your Answer


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.