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;

// Calculate total.
TotalCost = UnitPrice * 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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.