Title: Initialize DataGridView controls with objects in C#
This example shows how to easily initialize DataGridView controls to display the properties of items. This example uses the following OrderItem class. Notice that the constructor calculates the TotalCost from the Quantity and UnitPrice.
public 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 control.
// 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
}
);
}
}
The AddOrderItems method 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.
Download the example to experiment with it and to see additional details.
|