How to DataAdapter DataGridView - OLEDB

The OleDbDataAdapter plays a vital role in facilitating effective communication between the Dataset and the OLEDB Data Source by utilizing the OleDbConnection Object. The OleDbConnection Object, while responsible for establishing a connection and retrieving data, lacks specific information about the retrieved data. Similarly, the Dataset remains unaware of the Data Source from which the data originates. Consequently, it is the responsibility of the OleDbDataAdapter to seamlessly manage the communication between these two entities. This crucial task is facilitated by the TableMapping Collection.

To ensure a synchronized and coherent workflow, the InsertCommand, UpdateCommand, and DeleteCommand properties of the OleDbDataAdapter object are essential components that enable the database to be updated with the data modifications performed on the DataSet object.

OleDbDataAdapter object using a DataGridView

The following C# source code demonstrates how to effectively update a Dataset through the OleDbDataAdapter object using a DataGridView. To run this C# source code, create a new C# project, add two buttons and a DataGridView to the default Form1, and then copy and paste the provided source code.

Full Source C#
using System; using System.Data; using System.Data.OleDb; using System.Windows.Forms; namespace WindowsApplication1 { public partial class Form1 : Form { string connetionString; OleDbConnection connection; OleDbDataAdapter oledbAdapter; OleDbCommandBuilder oledbCmdBuilder; DataSet ds = new DataSet(); DataSet changes; int i; string Sql; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"; connection = new OleDbConnection(connetionString); Sql = "select * from tblUsers"; try { connection.Open(); oledbAdapter = new OleDbDataAdapter(Sql, connection); oledbAdapter.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; } catch (Exception ex) { MessageBox.Show (ex.ToString()); } } private void button2_Click(object sender, EventArgs e) { try { oledbCmdBuilder = new OleDbCommandBuilder(oledbAdapter); changes = ds.GetChanges(); if (changes != null) { oledbAdapter.Update(ds.Tables[0]); } ds.AcceptChanges(); MessageBox.Show("Save changes"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } }