none
Adding multiple items to SharePoint 2010 list Programmatically RRS feed

  • Question

  • Dear All,

    I've a scenario where i am having some data in asp.net list<> and using this list to create items in SharePoint 2010 List programmatically (VS 2010). the asp.net list<> is having item count = 2 but using the below code i am getting only second item create in SharePoint 2010 list;

    using (SPWeb sWeb1 = sSite1.OpenWeb())
                {
                    //SPListItemCollection inspectionList = sWeb1.Lists[workflowProperties.List.Title].Items;
                    SPList inventoryList1 = sWeb1.Lists["List"];
                    SPListItem itemtoAdd = inventoryList1.Items.Add();
                    sWeb1.AllowUnsafeUpdates = true;
                    foreach (AddItem item in addList)  // addList is asp.net list<>
                    {
                        
                        itemtoAdd ["Item"] = item.iTitle.ToString();
                        itemtoAdd ["Quantity"] = item.Qnty;
                        sWeb1.AllowUnsafeUpdates = true;
                        itemtoAdd .Update();
                        inventoryList1.Update();

                        
                    }
                }

    any suggestion.

    Regards,

    Suboor.

    Wednesday, May 9, 2012 2:45 PM

Answers

  • You should add new item to the list in each iteration, not just once before the cycle, like this:

      foreach (AddItem item in addList)  // addList is asp.net list<>

                    {
                        SPListItem itemtoAdd = inventoryList1.Items.Add();
                        itemtoAdd ["Item"] = item.iTitle.ToString();
                        itemtoAdd ["Quantity"] = item.Qnty;
                        sWeb1.AllowUnsafeUpdates = true;
                        itemtoAdd .Update();
                        inventoryList1.Update();
                    }


    -- Ilya

    • Proposed as answer by Aviw_ Wednesday, May 9, 2012 4:58 PM
    • Marked as answer by Suboor Ahmad Thursday, May 10, 2012 4:44 AM
    Wednesday, May 9, 2012 3:15 PM

All replies

  • You should add new item to the list in each iteration, not just once before the cycle, like this:

      foreach (AddItem item in addList)  // addList is asp.net list<>

                    {
                        SPListItem itemtoAdd = inventoryList1.Items.Add();
                        itemtoAdd ["Item"] = item.iTitle.ToString();
                        itemtoAdd ["Quantity"] = item.Qnty;
                        sWeb1.AllowUnsafeUpdates = true;
                        itemtoAdd .Update();
                        inventoryList1.Update();
                    }


    -- Ilya

    • Proposed as answer by Aviw_ Wednesday, May 9, 2012 4:58 PM
    • Marked as answer by Suboor Ahmad Thursday, May 10, 2012 4:44 AM
    Wednesday, May 9, 2012 3:15 PM
  • Thanks Ilya, thats the solution.
    Thursday, May 10, 2012 4:44 AM