2011-01-23 32 views
5

尝试在运行时向EntityCollection添加新记录并使用新信息更新DataGridView。如何在绑定到EntityCollection时显示新记录Windows窗体DataGridView

我试着将datagridview直接绑定到实体集合(即ObjectSet)并通过绑定到相同集合的BindingSource。我试过DataGridView.Refresh(),DataGridView.EndEdit()和BindSource.ResetBindings()等东西,但似乎没有任何工作。

回答

0

试一下:

bindingSource.DataSource = null; 
bindingSource.DataSource = theCollection; 

或者,你可以在一个BindingList<T>保持数据的内存副本。将DataGridView绑定到BindingList,并且当您将一个实体添加到ObjectSet时,也将它添加到BindingList

+0

又名贫民窟的道路,:)。希望有一种不太暴力的方法。这虽然不起作用,但因为我目前绑定到BindingSource。这导致网格被清除。 – Jaime 2011-01-23 17:29:35

0

我陷入了同样的问题。微软应该关心使用他们的技术的人,而EF应该关心数据绑定。海梅,如果你找到更好的方法,请更新此列表。对我来说,重新创建上下文实例对我来说工作得很好。有趣的是调试器显示实体上下文&绑定源具有最新的更新,但datagridview仍然不刷新。由于

Here是到目前为止,我已经找到了最佳的解决方案 -

基本上你需要做的

bindingSource.DataSource = EntityContext.Collection 
           .Execute(MergeOption.AppendOnly); 
0

我希望这不是为时已晚=)我有一些作品在这里...

// Entity Data Model 
private ManagerEntities context = new ManagerEntities(); 

// declare private member  
private BindingList<Currency> lstCurrencies = null; 

// on form load, load data and bind to DataGridView's DataSource 

private void Form1_Load(object sender, EventArgs e) { 

    lstCurrencies = new BindingList<Currency>(); 

    ObjectResult or = ((ObjectQuery)currencies).Execute(MergeOption.AppendOnly); 
    foreach (Currency c in or) 
     lstCurrencies.Add(c); 

    // dgMain is my DataGridView 
    dgMain.DataSource = lstCurrencies; 
} 

// this will save objects that have changed. You might want to add logic for newly created and deleted objects. 
private void btnSave_Click(object sender, EventArgs e) { 
    context.SaveChanges(); 
} 
相关问题