0

How to add a new item to SharePoint list in server object-model using C#.

This is my code and I want to delete just one item using listBox

    SPWeb web = SPContext.Current.Web;
    SPListItemCollection booksListaItems = web.Lists["Books"].GetItems();
    foreach(SPListItem item in booksListaItems)
    {
        lstItems.Items.Add(item.GetFormattedValue("Title"));
    }
0

2 Answers 2

0

Here is the modified version of your code for adding items to your list box. Note adding item IDs as the value:

SPWeb web = SPContext.Current.Web;
SPList booksList= web.Lists["Books"];
foreach(SPListItem item in booksList.Items)
{
    lstItems.Items.Add(new ListItem(item.GetFormattedValue("Title"),item.ID.ToString()));
}

Then let's say you have a "Delete" button with a Click event with this code:

SPWeb web = SPContext.Current.Web;
SPList booksList= web.Lists["Books"];
int itemId=0;
if (int.TryParse(lstItems.SelectedValue,out itemId))
{
    SPListItem itemToDelete=booksList.GetItemByID(itemId);
    itemToDelete.Delete();
}
0

Adding list item

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["Books"].Items;

SPListItem item = listItems.Add();

item["Title"] = "Title";

item.Update();

Deleting list items

SPWeb mySite = SPContext.Current.Web;
SPListItemCollection listItems = mySite.Lists["Books"].Items;
int itemCount = listItems.Count;

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

    listItems.Delete(k);
}
3
  • Thank you Amal Hushim for your answer but I want to delete just one item and not the all items. Mar 18, 2015 at 23:17
  • You can find the item to delete and pass it to the Delete method. Mar 18, 2015 at 23:18
  • How? if i use a listbox to show the item title as a string Mar 18, 2015 at 23:28

Your Answer

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

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