Updating MS Access Database from Datagridview

二次信任 提交于 2019-12-10 22:45:00

问题


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.


回答1:


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.




回答2:


dataadapter = new OleDbDataAdapter(sql, connection);

Add below code after above line, OleDbCommandBuilder will generate commands for you.

OleDbCommandBuilder cb = new OleDbCommandBuilder(dataadapter);

This tutorial will give you more information.



来源:https://stackoverflow.com/questions/9770561/updating-ms-access-database-from-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!