如何同步Database和DataGridView

El *_*Mac 3 c# sql-server datagridview visual-studio-2010 winforms

我一直在尝试通过a同步数据库DataGridView.到目前为止,我已经创建了一个数据模型类.此类包含与数据库匹配的多个属性.它们使用命名空间中的[Table][Column]属性进行映射System.Data.Linq.Mapping.

好.所以我DataGridViewDataSource-Property用于DataContext连接数据库(MSSQL).这个逻辑是在单例类中实现的,所以我可以保证有一个这样的实例DataContext.

 this.m_context = new DataContext(conn);
 this.m_VisitorTable = m_context.GetTable<Visitor>();
Run Code Online (Sandbox Code Playgroud)

好吧,如果我将表绑定到我,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");
    }
 }
Run Code Online (Sandbox Code Playgroud)

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

这是类声明:

[Table(Name = "tblVisitor")]
public class Visitor
Run Code Online (Sandbox Code Playgroud)

此外,我还没有找到更新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;
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

小智 5

您需要使用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;
Run Code Online (Sandbox Code Playgroud)

要更新您通常会调用的基础数据库

bindingsource.EndEdit();
dataAdapter.Update(dataTable);
Run Code Online (Sandbox Code Playgroud)

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

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

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