Bind a DataGridView control to a DataSet holding multiple tables at runtime in C#

When the form loads, the following code builds the DataSet and binds it to the form's DataGridView.
// The DataAdapters and the DataSet.
private OleDbDataAdapter DaAddresses, DaTestScores;
private DataSet DsContacts;

private void Form1_Load(object sender, EventArgs e)
{
const string SELECT_ADDRESSES = "SELECT * FROM Addresses";
const string SELECT_TEST_SCORES = "SELECT * FROM TestScores";

// Get the database file name.
// This assumes the database is in the executable directory.
string db_name = Application.StartupPath + "\\Contacts.mdb";

// Compose the connection string.
string connect_string =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + db_name + ";" +
"Persist Security Info=False";

// 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);

// Update the database.
try
{
DaAddresses.Update(DsContacts, "Addresses");
DaTestScores.Update(DsContacts, "TestScores");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

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.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.