View Relational Data in a DataGrid

This article explains to you how easy is to read a database and displaying in a grid using DataSet.
 
In this sample example, I have used the access 2000 database, Northwind.mdb. We access the Customers table of the Northwind database and display records in a datagrid control.
 
Starting: Create a Windows Application type project and add a DataGrid control to the form. Leave DataGrid name as DataGrid1.
 
Add Reference to the Namespace
 
First thing you need to do is add a reference to System.Data.OleDb namespace since I will use OldDb data providers. if System.Data namespace is not present, you might want to add this too.
  1. using System.Data.OleDb; 
Create OleDbDataAdapter Object
 
Now you create a OleDbDataAdapter object and connect to a database table.
  1. // create a connection string  
  2. string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";  
  3. OleDbConnection myConnection = new OleDbConnection();  
  4. myConnection.ConnectionString = connString;// create a data adapter OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", myConnection);  
Create a DataSet Object and Fill with the data
 
You use Fill method of OleDbDataAdpater to fill data to a DataSet object.
  1. // create a new dataset  
  2. DataSet ds = new DataSet();  
  3. // fill dataset  
  4. da.Fill(ds, "Customers");// write dataset contents to an xml file by calling WriteXml method  
Attach DataSet to DataGrid
 
Now you use DataSource method of DataGrid to attached the DataSet data to the data grid.
  1. // Attach DataSet to DataGrid  
  2. dataGrid1.DataSource = ds.DefaultViewManager;  
Here is entire source code written on the form load method.
  1. private void Form1_Load(object sender, System.EventArgs e) {  
  2.     // create a connection string  
  3.     string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";  
  4.     OleDbConnection myConnection = new OleDbConnection();  
  5.     myConnection.ConnectionString = connString; // create a data adapter OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", myConnection);  
  6.     // create a new dataset  
  7.     DataSet ds = new DataSet();  
  8.     // fill dataset  
  9.     da.Fill(ds, "Customers"); // write dataset contents to an xml file by calling WriteXml method  
  10.     // Attach DataSet to DataGrid  
  11.     dataGrid1.DataSource = ds.DefaultViewManager;  
The output of the program looks like the following figure.
 
data_v1.gif