2011-01-23 33 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(); 
} 
相關問題