简体   繁体   English

C#和msaccess,保存Datagrid

[英]C# and msaccess, save Datagrid

I writing an adressbook (with a datagrid view in it. When changing the cells in the datagrid there is a possibility to save the changes. Therefore I have the following code: 我写了一个地址簿(其中有一个数据网格视图。更改数据网格中的单元格时,可以保存更改。因此,我有以下代码:

private void btnSaveGrid_Click(object sender, EventArgs e) 
{
    try 
    {
        OleDbConnection cn = new OleDbConnection();
                OleDbCommand cmd = new OleDbCommand();
                cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myDatabase.accdb;Persist Security Info=False;";
                cn.Open();

                cmd.Connection = cn;
                cmd.CommandText = " SELECT * FROM myTable ";

                OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd.CommandText, cn);
                OleDbCommandBuilder builder = new OleDbCommandBuilder(dAdapter);

                dAdapter.Update(dTable); 
                cn.Close();
                MessageBox.Show("Information update", "Update", MessageBoxButtons.OK, MessageBoxIcon.Information);

    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

}

the dTable is (DataTable dTable = new DataTable(); is writen before the InitializeComponent. dTable是(DataTable dTable = new DataTable();在InitializeComponent之前写入。

Now the problem is that when the cells are changed in the datagrid view but the databases isn't update with the new information! 现在的问题是,当在数据网格视图中更改了单元格,但数据库未使用新信息进行更新时! The messagebox didn't give an Error but the information Update. 该消息框没有给出错误,但给出了信息更新。

What Iam doing wrong?? 我做错了什么?

Thanks in advance 提前致谢

Refer to this documentation : Updating data sources with DataAdapter 请参阅此文档: 使用DataAdapter更新数据源

You first need to write your own update logic in order to make it work. 首先,您需要编写自己的更新逻辑以使其工作。

And of course as @Crowcoder mentioned you also need to bind data to the DataTable with fill command before doing any updates... 当然,正如@Crowcoder提到的那样,在进行任何更新之前,您还需要使用fill命令将数据绑定到DataTable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM