![](/img/trans.png)
[英]How to do Automatic synchronize between database access and DatagridView in c#
[英]How to synchronize Database and DataGridView
我一直在嘗試通過DataGridView
同步數據庫。 到目前為止,我已經創建了一個數據模型類。 此類包含與數據庫匹配的多個屬性。 它們使用System.Data.Linq.Mapping
命名空間中的[Table]
和[Column]
屬性進行映射。
好。 所以我使用DataSource
-Property將DataGridView
綁定到連接到數據庫(MSSQL)的DataContext
。 這個邏輯是在單例類中實現的,所以我可以保證這個DataContext
有一個實例。
this.m_context = new DataContext(conn);
this.m_VisitorTable = m_context.GetTable<Visitor>();
好吧,如果我將表綁定到DataGridView.DataSource
我可以看到數據庫中的所有條目都已加載並正確顯示。 然后,如果我改變了一些東西,我發現自己面臨同步問題。 更改的單元格在數據庫端沒有更改。
為了保存更改,我實現了這個方法:
public void SaveChanges()
{
try
{
// I have no idea what I'm doing here.
VisitorLogic.Instance.m_VisitorTable.Context.SubmitChanges(System.Data.Linq.ConflictMode.Con
// I'm also trying to see if changes were made so I can save them before closing.
this.m_bChangesMade = false;
}
catch (Exception ex)
{
MessageBox.Show("Failed to save.", "Error");
}
}
有沒有辦法讓數據庫的整個同步自動發生? 就像改變自動提交一樣。 我想我將不得不改變模型類的東西。 現在,它沒有實現任何接口也沒有繼承任何東西。
這是類聲明:
[Table(Name = "tblVisitor")]
public class Visitor
此外,我還沒有找到一種方法來“正確”更新我的DataGridView
。 這就是我現在制作它的方式,但它似乎並不總是有效。 有一個更好的方法嗎?
// Retrieve the new data from the database
VisitorLogic.Instance.m_VisitorTable.Context.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, VisitorLogic.Instance.m_VisitorTable);
// Set the DataSource to 'null'
this.dataGridView.DataSource = null;
// Refresh (?!)
this.dataGridView.Refresh();
// Bind the new DataSource, hoping it will show the new data.
this.dataGridView.DataSource = VisitorLogic.Instance.m_VisitorTable;
this.m_bChangesMade = false;
謝謝你的幫助!
您需要使用BindingSource對象。 這將使您的DataTable與DataGridView保持同步。
因此,將BindingSource的DataSource設置為表,然后將DataGridView的DataSource設置為BindingSource。
例:
// DataGridView
DataGridView dg = new DataGridView();
// BindingSource (used for synchronizing table and grid)
BindingSource bs = new BindingSource();
// Set DataSource of BindingSource to table
bs.DataSource = table;
// Set grid DataSource
dg.DataSource = bs;
要更新您通常會調用的基礎數據庫
bindingsource.EndEdit();
dataAdapter.Update(dataTable);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.