如何同步Database和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(); 

好吧,如果我将表绑定到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"); } } 

有没有办法让数据库的整个同步自动发生? 就像改变自动提交一样。 我想我将不得不改变模型类的东西。 现在,它没有实现任何接口也没有inheritance任何东西。

这是类声明:

 [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); 

这是一个关于绑定源对象的教程和更深入的信息:

将数据从应用程序保存到数据库(msdn):

C#中使用LINQ to SQL进行数据绑定