Issue with List.Add() only saving the last added item

c#

Solution

You need to instantiate the `Orderables` within the for loop; otherwise, you keep reusing the same instance in all iterations (and overwriting its properties each time).

AssociatedComboItems ai = new AssociatedComboItems();
List<Orderables> tempList = new List<Orderables>();

foreach (var t in comboBox1.Items)
{
    ai.ComboBoxItem = t.ToString();

    for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++)
    {
        Orderables orderables = new Orderables();  // ← Instantiate here
        orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text;
        orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value;
        orderables.DisplayOrder = i;
        tempList.Add(orderables);
    }

    ai.AssociatedItems = tempList;
    tempList.Clear();
    if(AssociatedItems == null)
    AssociatedItems = new List<AssociatedComboItems>();
    AssociatedItems.Add(ai);
}

Unrelated to the question: You might find object initializer syntax to be cleaner:

Orderables orderables = new Orderables
{
    Display = fpSpread1.ActiveSheet.Cells[i, 1].Text,
    ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value,
    DisplayOrder = i,
};

Problem

The issue I'm noticing is this line of code: ``` tempList.Add(orderables); ``` In this full code: ``` AssociatedComboItems ai = new AssociatedComboItems(); List<Orderables> tempList = new List<Orderables>(); Orderables orderables = new Orderables(); foreach (var t in comboBox1.Items) { ai.ComboBoxItem = t.ToString(); for (int i = 0; i < fpSpread1.ActiveSheet.RowCount; i++) { orderables.Display = fpSpread1.ActiveSheet.Cells[i, 1].Text; orderables.ShowInDSR = (bool)fpSpread1.ActiveSheet.Cells[i, 0].Value; orderables.DisplayOrder = i; tempList.Add(orderables); } ai.AssociatedItems = tempList; tempList.Clear(); if(AssociatedItems == null) AssociatedItems = new List<AssociatedComboItems>(); AssociatedItems.Add(ai); } ``` When I put my breakpoint on the line mentioned above (`tempList.Add(orderables);` ), the first time it adds the item correctly to the `templist` and it will have one item in it. The second time it will add the correct item to the list but if I hover over `tempList` and want to see its contents, although it has two items, both of them are the same - they are both now the second item that was added to the list. It has overwritten the first one. I can't figure out what is going wrong with this and why it is happening.

Original source

Related problems