1

我正在尝试制作一个简单的 winform 应用程序,我可以在其中读取/更新数据并将数据插入 MS Access db 表

当我运行应用程序时,它会从 MS Access db 读取数据,我可以添加新数据或编辑现有数据,但这些更改不会发送回 DB。

我的保存按钮单击事件中的代码

    Validate();
    myBindingSource.EndEdit();

    //myTableAdapterManager.UpdateAll(myDataSet.myTable); //this line was in generated code
    myTableAdapter.Update(myDataSet.myTable); //replaced previous row with this one, but with no effect

当我按下“保存”按钮时

我没有收到任何错误消息,在 DataGridView 中,新行包含具有 -1 值的 ID,并且新行未添加到数据库中

可能是什么问题呢?我错过了什么?

当我从 MS Access 2007 打开 mdb 文件时,可以向该表添加新行

这个 SO post 似乎是关于同样的问题,但它对我的情况没有帮助

无法在 Winforms 中使用 C# 使用 datagridview 添加新行

[编辑]

我打开了 .xsd 文件并为 myTable 添加了插入和更新查询,但这仍然无济于事 - 当我按下保存按钮时,更改不会发送到数据库

4

1 回答 1

0

我找到了如何将数据从网格控件发送到数据库的解决方案,我希望它也能对其他人有所帮助(+添加了一些有用的附加内容)

这是我的代码

//form level fields
        OleDbConnection conn = new OleDbConnection();
        OleDbDataAdapter adapter;// = new OleDbDataAdapter();
        DataTable table = new DataTable();
        BindingSource bSource = new BindingSource();

//choosing MS Access file 
        var ecgDbFile = new OpenFileDialog();
        ecgDbFile.InitialDirectory = "c:\\";
        ecgDbFile.Filter = @"MS Access files (*.mdb)|*.mdb";
        ecgDbFile.FilterIndex = 1;
        ecgDbFile.RestoreDirectory = true;

//creating connection
        conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ecgDbFile.FileName;
        conn.Open();

//A nice way how to get a list of Data base's tables
        var restrictions = new string[4];
        restrictions[3] = "Table";
        userTableList = conn.GetSchema("Tables", restrictions);
//then loop through and you can get table names => userTableList.Rows[i][2].ToString()

//reading the data (in the grid)
        adapter = new OleDbDataAdapter("Select * from "+TableName, conn);
        adapter.Fill(table);
        bSource.DataSource = table; //binding through bindingsource
        GridControl.DataSource = bSource; //actually it works fine if GridControl.DataSource is set to table directly as well...

//choose the appropriate trigger (some gridcontrol or button click event) to call for database updates
    private void GridControl_Leave(object sender, EventArgs e)
    {
        //because of this OleDbCommandBuilder TableAdapter knows how to insert/update database
        OleDbCommandBuilder command = new OleDbCommandBuilder(adapter);
        adapter.Update(table);
    }
于 2013-09-24T21:17:01.593 回答