-1

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

This is my code and I want to add items using textboxes

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

1 Answer 1

1

Use this:

SPListItem newItem = lstItems.AddItem();
newItem["Title"] = "New Title"; 
newItem.Update(); 

Once you get a reference to the item, update the columns, then call the Update method to save your changes.

3
  • It Works thank you but I did that SPListItem newItem = web.Lists["Books"].AddItem(); newItem["Title"] = "New Title"; newItem.Update(); because lstItems just a listbox with shows all items but Books is my my listname Commented Mar 18, 2015 at 9:41
  • Do you know how to delete it now if i use a listbox to show all the items Title? Commented Mar 18, 2015 at 22:28
  • The best thing is to give the user the ability to provide the Item ID, so you could get the item using its ID then call the Delete method on it. It's safer to get the item by ID than doing it on other columns as it would make the item retrieval unique. The syntax would be: YourList.GetItemById(5).Delete()
    – user19105
    Commented Mar 19, 2015 at 4:12

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.