[C# Helper]
Index Books FAQ Contact About Rod
[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[Beginning Software Engineering]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Initialize DataGridView controls with objects in C#

initialize DataGridView controls

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.

© 2009-2022 Rocky Mountain Computer Consulting, Inc. All rights reserved.