MIcheal David
MIcheal David

Reputation: 149

How to add to List Generic on each button clicks

I have a button that gets items from controls and add to a list. As shown

This is my ojects thats holds the values.

public class SelectedPurchaseItems
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public double PurchasePrice { get; set; }
    public int Quantity { get; set; }
    public string UnitOfMeasure { get; set; }
    public double Total { get; set; }
}

This is my mainwindow class that does the adding to the list

public partial class MainWindow : Window
{ 
    public List<SelectedPurchaseItems> SelectedList;

    private void btnSaveModalSelectItem_Click(object sender, RoutedEventArgs e)
    {  
            SelectedList = new List<SelectedPurchaseItems>();
            SelectedPurchaseItems _value = new SelectedPurchaseItems()
            {
                ItemId = Convert.ToInt32(comboboxSelectItemItem.SelectedValue),
                ItemName = comboboxSelectItemItem.Text,
                PurchasePrice = _purchasePrice,
                Quantity = _quantity,
                UnitOfMeasure = comboboxSelectItemUnitofMeasure.Text,
                Total = _total
            };
            SelectedList.Add(_value);
            DataGridSelectedPurchaseItems.ItemsSource = SelectedList;
    }
}

My challenge now is, any time it adds an item to the List, it always reinitialize the list, which makes the previous item added to clear off. But my aim is for the List to hold each item that has been added to it, and i don't know how to go about that.

I'm also Binding the list to a WPF datagrid. So after showing the first added item, it won't display any further added item.

Upvotes: 1

Views: 107

Answers (2)

Jeremy Thompson
Jeremy Thompson

Reputation: 65672

Dont re-instantiate it in the button click. Simply initialise it once as shown:

public partial class MainWindow : Window
{ 
    public List<SelectedPurchaseItems> SelectedList = new List<SelectedPurchaseItems>();
    public MainWindow()
    {
        DataGridSelectedPurchaseItems.ItemsSource = SelectedList;
    }

    private void btnSaveModalSelectItem_Click(object sender, RoutedEventArgs e)
    {  
        SelectedPurchaseItems _value = new SelectedPurchaseItems()
        {
            ItemId = Convert.ToInt32(comboboxSelectItemItem.SelectedValue),
            ItemName = comboboxSelectItemItem.Text,
            PurchasePrice = _purchasePrice,
            Quantity = _quantity,
            UnitOfMeasure = comboboxSelectItemUnitofMeasure.Text,
            Total = _total
        };
        SelectedList.Add(_value);
    }
}

Upvotes: 0

Dmitry Pavlushin
Dmitry Pavlushin

Reputation: 612

SelectedList = new List<SelectedPurchaseItems>();

is the line that reinitializes your list. You should just delete it, and move initial list initialization to a constructor or somwhere else

Upvotes: 1

Related Questions