BLOG.CSHARPHELPER.COM: Use an array of objects to initialize a DataGridView in C#
Use an array of objects to initialize a DataGridView in C#
This example uses the following OrderItem class. Notice that the constructor calculates the TotalCost from the Quantity and UnitPrice.
class OrderItem { public string Description; public int Quantity; public decimal UnitPrice, TotalCost; public OrderItem(string new_description, decimal new_unitprice, int new_quantity) { Description = new_description; UnitPrice = new_unitprice; Quantity = new_quantity;
The form's Load event handler creates an array of OrderItem objects. It then calls the following AddOrderItems method to add the items to the DataGridView.
// Add the items to the DataGridView. private void AddOrderItems(OrderItem[] order_items) { foreach (OrderItem item in order_items) { dgvValues.Rows.Add(new object[] { item.Description, item.UnitPrice, item.Quantity, item.TotalCost } ); } }
AddOrderItems loops through the items. For each item, it creates an array of objects holding the item's values and adds the array to the DataGridView control.
Your experience is great and learning for other people.
Reply to this