从DataGridView更新MS Access数据库 [英] Updating MS Access Database from Datagridview

查看:284
本文介绍了从DataGridView更新MS Access数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新从一个DataGridView MS Access数据库。

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

在DataGridView填充点击一个按钮,当任何细胞被修改更新数据库。

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

中的代码示例中,我使用的形式负载填充了和使用cellendedit事件。

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

更新要求当传递的DataRow集合
与修改行有效的UpdateCommand。

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.

推荐答案

该dbDataAdapterClass(就是那个OleDbDataAdapter的继承)具有的SelectCommand,的UpdateCommand和InsertCommand会。这是一个负责选择,更新和插入,当你明确调用任何方法(例如更新;))。
因为在你的代码,你永远不提供解释如何执行更新的命令时,DataAdapter不知道该怎么做。

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.

所以满足要求,增加一个update命令到适配器。

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

这篇关于从DataGridView更新MS Access数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆