我写了一个地址簿(里面有数据网格视图。当更改数据网格中的单元格时,有可能保存 变化。因此,我有以下代码:
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);
}
}
dTable是(DataTable dTable = new DataTable();在InitializeComponent之前写入。
现在的问题是,在数据网格视图中更改单元格但数据库不会使用新信息进行更新! 消息框没有给出错误,但信息更新。
我做错了什么?
提前致谢
答案 0 :(得分:0)
请参阅此文档: Updating data sources with DataAdapter
首先需要编写自己的更新逻辑才能使其正常工作。
当然,正如@Crowcoder所提到的,在进行任何更新之前,你还需要使用fill命令将数据绑定到DataTable ......