Updating MS Access Database from Datagridview

10,938

The dbDataAdapterClass (the one that OleDbDataAdapter inherit from) has a SelectCommand, UpdateCommand and InsertCommand. This are the one responsible for select, update, and insert when you explicit call any of the methods (for example update ;) ). Since in your code, you never provide the command that explain how to do the update, the dataadapter doesn't know how to do it.

so fulfill the requirements, adding an update command to the adapter.

Share:
10,938
Peter Roche
Author by

Peter Roche

Updated on June 04, 2022

Comments

  • Peter Roche
    Peter Roche almost 2 years

    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.

  • Conrad Frix
    Conrad Frix about 9 years
    Rather than adding an update command to the adapter. I would say set the UpdateCommand property