// Get the database file name. // This assumes the database is in the executable directory. string db_name = Application.StartupPath + "\\Contacts.mdb";
// Create a DataAdapter to load the Addresses table. DaAddresses = new OleDbDataAdapter(SELECT_ADDRESSES, connect_string);
// Create a DataAdapter to load the Addresses table. DaTestScores = new OleDbDataAdapter(SELECT_TEST_SCORES, connect_string);
// Create and fill the DataSet. DsContacts = new DataSet(); DaAddresses.Fill(DsContacts, "Addresses"); DaTestScores.Fill(DsContacts, "TestScores");
// Bind the DataGrid to the DataSet. dgContacts.DataSource = DsContacts; }
The code composes a database connect string and then creates two OleDbDataAdapters to select data from the database's Addresses and TestScores tables. It creates a new DataSet and then uses the data adapters to load their tables in it. Finally the code sets the DataGridView's DataSource property to the DataSet. The DataGridView automatically lets the user open either table and edit values.
When the user closes the form, the following code saves any changes in the data back to the database.
// Save changes to the data. private void Form1_FormClosing(object sender, FormClosingEventArgs e) { // Use a CommandBuilder to make the INSERT, // UPDATE, and DELETE commands as needed. OleDbCommandBuilder command_builder; command_builder = new OleDbCommandBuilder(DaAddresses); command_builder = new OleDbCommandBuilder(DaTestScores);
This code creates a command builder object to automatically generate database commands as needed while updating the data. (When you create a command builder, it is attached to the data adapter you pass to the constructor. That's how the adapter later can generate the commands it needs. It's a bit mysterious.)
The code then calls each data adapter's Update method to update the database.
Good example. Thanks.!
Reply to this