Updating MS Access Database from Datagridview

Posted by Peter Roche on Stack Overflow See other posts from Stack Overflow or by Peter Roche
Published on 2012-03-19T12:53:35Z Indexed on 2012/11/06 5:01 UTC
Read the original article Hit count: 305

I am trying to update an ms access database from a datagridview.

The datagridview is populated on a button click and the database is updated when any cell is modified.

The code example I have been using populates on form load and uses the cellendedit event.

private OleDbConnection connection = null;
private OleDbDataAdapter dataadapter = null;
private DataSet ds = null;
private void Form2_Load(object sender, EventArgs e)
{

    string connetionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\\Users\\Peter\\Documents\\Visual Studio 2010\\Projects\\StockIT\\StockIT\\bin\\Debug\\StockManagement.accdb';Persist Security Info=True;Jet OLEDB:Database Password=";
    string sql = "SELECT * FROM StockCount";
    connection = new OleDbConnection(connetionString);
    dataadapter = new OleDbDataAdapter(sql, connection);
    ds = new DataSet();
    connection.Open();
    dataadapter.Fill(ds, "Stock");
    connection.Close();

    dataGridView1.DataSource = ds;
    dataGridView1.DataMember = "Stock";

}
private void addUpadateButton_Click(object sender, EventArgs e)
{

}

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    try
    {
        dataadapter.Update(ds,"Stock");
    }
    catch (Exception exceptionObj)
    {
        MessageBox.Show(exceptionObj.Message.ToString());
    }
}

The error I receive is

Update requires a valid UpdateCommand when passed DataRow collection with modified rows.

I'm not sure where this command needs to go and how to reference the cell to update the value in the database.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql