MIcheal David MIcheal David -4 years ago 76
C# Question

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.

Answer Source
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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download