I decided to make a small project about Voltage Stabilizer. I tried to insert data from ComboBox to DataGrid in WPF.
I created Invoice class:
public class Invoice
{
public string Number { get; set; }
public string Item { get; set; }
public string Power { get; set; }
public string Quantity { get; set; }
}
I using a List to insert information to DataGrid.
List<Invoice> ItemCollection = new List<Invoice>()
{
new Invoice() {Number = num, Item = equipment.Text, Power = power.Text, Quantity = quantity.Text}
};
DataGrid.Items.Add(ItemCollection);
But if I make the equipment, power and quantity ComboBoxex data print out in the DataGrid, I get wrong result:
System.Collections.Generic.List`1[VoltageStablizer.EnterParams+Invoice]
Type of items in DataGrid.Items
is DataGridItem Which means you can't directly add another collection with different type.
On the other hand, assigning IEnumerable
(ItemCollection
in your case) to DataGrid.ItemsSource
automatically generates columns for DataGrid
.
When adding new item to list, you can just add it to ItemCollection
. Also create a property in your container for ItemCollection
, so you can use in different parts of your code.
// When initializing your container
ItemCollection = new List<Invoice>();
DataGrid.ItemsSource = ItemCollection;
// When add button clicked
ItemCollection.Add(new Invoice() {Number = num, Item = equipment.Text, Power = power.Text, Quantity = quantity.Text});