CHAPTER 22 ADO.NET PART II: THE DISCONNECTED LAYER
}
dataGridViewOrders.DataSource = autoLotDS.Tables["Orders"];
Building the Table Relationships
The BuildTableRelationship() helper function does the grunt work to add two DataRelation objects into
the autoLotDS object. Recall from Chapter 21 that the AutoLot database expresses a number of
parent/child relationships, which you can account for with the following code:
private void BuildTableRelationship()
{
// Create CustomerOrder data relation object.
DataRelation dr = new DataRelation("CustomerOrder",
autoLotDS.Tables["Customers"].Columns["CustID"],
autoLotDS.Tables["Orders"].Columns["CustID"]);
autoLotDS.Relations.Add(dr);
// Create InventoryOrder data relation object.
dr = new DataRelation("InventoryOrder",
autoLotDS.Tables["Inventory"].Columns["CarID"],
autoLotDS.Tables["Orders"].Columns["CarID"]);
autoLotDS.Relations.Add(dr);
}
Note that you establish a friendly string moniker with the first parameter when you create a
DataRelation object (you’ll see the usefulness of doing so in just a minute). You also establish the keys
used to build the relationship itself. Notice that the parent table (the second constructor parameter) is
specified before the child table (the third constructor parameter).
Updating the Database Tables
Now that the DataSet has been filled with data from the data source, you can manipulate each DataTable
locally. To do so, run the application and insert, update, or delete values from any of the three
DataGridViews. When you are ready to submit the data back for processing, click the Update button. You
should find it easy to follow along with the code behind the related Click event at this point.
private void btnUpdateDatabase_Click(object sender, EventArgs e)
{
try
{
invTableAdapter.Update(autoLotDS, "Inventory");
custTableAdapter.Update(autoLotDS, "Customers");
ordersTableAdapter.Update(autoLotDS, "Orders");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Now run your application and perform various updates. When you rerun the application, you
should find that your grids are populated with the recent changes.
899