我已经能够将我的 MS Access 数据库中的数据绑定到表单上的文本框。但是当我更新数据时,不会对数据库进行任何更改。我做了一个简化的例子来演示我的问题。该表单仅包含两个文本框(txtFirstName 和 txtLastName)和两个按钮(保存和刷新)。刷新只是从数据库中重新加载 DataTable。我加载 ID 为 1 的记录并尝试更新。代码如下。我知道对文本框的更新也会更新 DataTable。但是,数据适配器的 Update 函数什么也不做,因为 OleDbCommandBuilder 不会生成 Update 命令。谁能告诉我我做错了什么?
非常感谢!
// Global data
public DataTable CaseTable = new DataTable();
private OleDbCommand dbCmd;
private OleDbDataAdapter adapter;
private OleDbCommandBuilder builder;
private OleDbConnection dbConn = null;
public frmCustomer()
{
InitializeComponent();
CaseTable.Columns.Add("ID");
CaseTable.Columns.Add("FirstName");
CaseTable.Columns.Add("LastName");
this.txtFirstName.DataBindings.Add("Text", CaseTable, "FirstName"); //, true, DataSourceUpdateMode.OnPropertyChanged);
this.txtLastName.DataBindings.Add("Text", CaseTable, "LastName"); //, true, DataSourceUpdateMode.OnPropertyChanged);
}
private void frmCustomer_Load(object sender, EventArgs e)
{
dbConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Customers.accdb");
dbCmd = new OleDbCommand("Select * From Customers Where ID = 1", dbConn);
adapter = new OleDbDataAdapter(dbCmd);
builder = new OleDbCommandBuilder(adapter);
RefreshForm();
}
private void RefreshForm()
{
CaseTable.Clear();
adapter.Fill(CaseTable);
if (CaseTable.Rows.Count < 1)
{
MessageBox.Show("Item Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (adapter.Update(CaseTable) < 1)
MessageBox.Show("No updates");
}
private void btnRefresh_Click(object sender, EventArgs e)
{
RefreshForm();
}