Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.
SPWeb web = SPContext.Current.Web;
    SPList list = web.Lists["MyList"];
    if (list != null)
    {
        for (int i = list.ItemCount - 1; i >= 0; i--)
        {
            list.Items[i].Delete();
        }
        list.Update();
    }

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

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");
if(list==null)
    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)
{
    item.Delete();
    break; // If you want to delete ONLY the first occurence.
}
list.Update();

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:

list.Items.DeleteItemById(SelectedId);
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.

Example:

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())
    {
        listItems.Delete(k);
        break; // Only break away if you want to delete one item ONLY!
    }
}

Source

share|improve this answer
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 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

 
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.