2012-08-03 73 views
3

我與實體框架一個簡單的項目,我有我的Form一個DataGridView,我設置其AllowUserToAddRow屬性true但我仍然不能添加新的行到它。的DataGridView AllowUserToAddRow屬性不起作用

這裏是我的代碼:

DBEntities context = new DBEntities(); 
private void Form1_Load(object sender, EventArgs e) 
{ 
    var q = (from i in context.myTable 
      select i).ToList(); 
    DataGridView.DataSource = q; 
} 

private void btnSave_Click(object sender, EventArgs e) 
{ 
    context.SaveChanges(); 
    MessageBox.Show("saved successfully"); 
} 

如果我使用一個BindingSource控制,它讓我插入行中DataGridView但這種方法後,我打電話context.SaveChanges()沒有插在我的數據庫文件。所以我想也許它相對於這個問題DataGridViewtrueAllowUserToAddRow屬性不讓我插入行DataGridView

回答

2

你的問題是你打電話給.ToList()並且實現你的查詢 - 這似乎打破了完整的數據綁定。

應該能夠簡單地有:

DBEntities context = new DBEntities(); 
private void Form1_Load(object sender, EventArgs e) 
{ 
    var q = (from i in context.myTable 
      select i); 
    DataGridView.DataSource = q; 
} 

我嘗試這樣做,它允許新行(你需要在你的表的主鍵,但是你應該有反正工作正常)。


請注意:此行爲在實體框架是有意打破4.1 - Webforms data binding with EF Code-First Linq query error


我說應該在我的答案,因爲我其實是有點驚訝它是這個簡單。我記得它在早期版本的實體框架中不能很好地工作,並且我沒有非常使用4.0。

如果上述解決方案不工作,你可能必須把這個做硬盤的方式,並在保存之前自己添加新的對象:

先介紹一個綁定源並在保存這樣做(與假想實體在本例中的客戶)的:

foreach (Customer customer in bs.List) 
{   
    // In my db customerId was an identity column set as primary key 
    if (customer.CustomerId == 0) 
     context.Customers.AddObject(customer); 
} 
context.SaveChanges(); 
+0

非常感謝。問題出在'ToList()'方法。我刪除了'ToList()'方法,現在可以在插入或刪除時正常工作。但是如果你在'DataGridView'中有自動增加(pk)列,它仍然會在插入時拋出一個異常。你有什麼建議如何處理這個異常? – 2012-08-03 20:08:15

+0

@masoudkeshavarz你的意思是你的數據庫表有一個自動增量標識列作爲主鍵?這對我來說很好。什麼是例外?可能最好問這是一個新問題。 – 2012-08-03 20:13:23

+0

'更新條目時發生錯誤。詳情請看內部例外情況。「好的,我可以問一個新問題。非常感謝:) – 2012-08-03 20:40:33

0

如果要將dataGridView綁定到源,那麼插入行的唯一適當方式是向DataGridView綁定到的數據結構添加一行。

+0

非常感謝你,願你告訴我一個例子嗎? – 2012-08-03 18:14:45

+0

@masoudkeshavarz我將在我的答案中編寫一個示例 – phadaphunk 2012-08-03 18:46:11

+0

這不是事實 - DataGridView旨在允許用戶使用UI將行添加到綁定的數據源,實際上這可能是該控件的最標準用法。 – 2012-08-03 19:37:10

2

我剛剛從痛苦4升級到EF 6,我有一個類似的問題,在EF6解決方案低於,我已顯示出進一步的幫助一個where語句。

DBEntities context = new DBEntities(); 
private void Form1_Load(object sender, EventArgs e) 
{ 
    context.MyTable.Where(e => e.myField == 1).Load(); 

    BindingSource bs = new BindingSource(); 
    bs.DataSource = context.MyTable.Local.ToBindingList(); 
    myDatagridView.DataSource = bs; 
} 

您現在可以使用context.SaveChanges();保存更改或插入

1

我遇到了Interbase方言的自定義數據庫實現的類似問題。 對我來說,解決方案是類似於上面:

var tableAList = _dbImplementation.SelectAll<TableA>().ToList(); 
var bindingSource = new BindingSource(); 
bindingSource.DataSource = typeof (TableA); 
foreach (var tableA in tableAList) 
{ 
    bindingSource.Add(tableA); 
} 
dataGridView.DataSource = bindingSource; 

有益的參考:A Detailed Data Binding Tutorial