[英]How to properly commit bindingSource changes to source DB?
我設置了DataGridView和其他UI組件,以允許用戶編輯來自SQLite DB的數據。 但是這些更改(即使它們在應用程序中正確顯示)也不會保存到DB。 我試過這段代碼
aBindingSource.EndEdit();
dbDataSetA.GetChanges();
aTableAdapter.Update(dbDataSetA.Accounts);
但是有並發異常:
System.Data.DBConcurrencyException未處理Message =並發沖突:UpdateCommand影響了預期的1條記錄中的0條。
那么我應該如何將綁定源更改提交給DB,伙計們呢?
POST EDIT我啟動程序時遇到此異常,然后單擊DataGridView中的第二行,然后單擊第三行,此時程序引發並發異常。 希望他的幫助能讓這個問題更加詳細。
先謝謝你們!
像這樣的東西?
try
{
aBindingSource.EndEdit();
dbDataSetA.GetChanges();
aTableAdapter.Update(dbDataSetA.Accounts);
}
catch (DBConcurrencyException exc)
{
MessageBox.Show("original data changed, please redo updates");
aTableAdapter.Fill(dbDataSetA);
}
然后根據需要將dbDataSetA重新分配為DataSource,用戶必須再次輸入數據。
有同樣的問題。 訣竅是,一旦你更新表,你應該“清空” GetChanges()
。 你可以通過調用方法AcceptChanges()
做到這一點。 所以...
aBindingSource.EndEdit();
dbDataSetA.GetChanges();
aTableAdapter.Update(dbDataSetA.Accounts);
dbDataSetA.AcceptChanges();
它應該工作,只要它是同樣的問題。
您可以將Adapter與命令構建器結合使用,如下所示:
DataTable table = new DataTable();
var adapter = new SqlDataAdapter("SELECT * FROM ...", con))
//Load the dataTable and the bound datagridView
adapter.Fill(table);
using (new SqlCommandBuilder(adapter))
{
//When done you can update the database using the Command builder
adapter.Update(table);
}
也許超大,但你可以嘗試使用交易只是閱讀這篇文章,可能會有所幫助:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.