CHAPTER 22 ADO.NET PART II: THE DISCONNECTED LAYER
private void CreateDataTable()
{
// Create table schema.
DataColumn carIDColumn = new DataColumn("ID", typeof(int));
DataColumn carMakeColumn = new DataColumn("Make", typeof(string));
DataColumn carColorColumn = new DataColumn("Color", typeof(string));
DataColumn carPetNameColumn = new DataColumn("PetName", typeof(string));
carPetNameColumn.Caption = "Pet Name";
inventoryTable.Columns.AddRange(new DataColumn[] { carIDColumn,
carMakeColumn, carColorColumn, carPetNameColumn });
// Iterate over the List to make rows.
foreach (Car c in listCars)
{
DataRow newRow = inventoryTable.NewRow();
newRow["ID"] = c.ID;
newRow["Make"] = c.Make;
newRow["Color"] = c.Color;
newRow["PetName"] = c.PetName;
inventoryTable.Rows.Add(newRow);
}
}
// Bind the DataTable to the carInventoryGridView.
carInventoryGridView.DataSource = inventoryTable;
The method implementation begins by creating the schema of the DataTable by creating four
DataColumn objects (for the sake of simplicity, you don’t need to bother autoincrementing the ID field or
set it as a primary key). After you do this, you can add them to the column collection of the DataTable
member variable. You map the row data from your List collection into the DataTable using a
foreach iteration construct and the native ADO.NET object model.
However, notice that the final code statement within the CreateDataTable() method assigns the
inventoryTable to the DataSource property of the DataGridView object. This single property is all you
need to set to bind a DataTable to a Windows Forms DataGridView object. Under the hood, this GUI
control reads the row and column collections internally, much like what happens with the
PrintDataSet() method of the SimpleDataSet example. At this point, you should be able to run your
application and see the DataTable within the DataGridView control, as shown in Figure 22-6.
880