2011-08-17 28 views
1

我想從gridview和數據庫中刪除一行 - 我寫了一些代碼,但是這段代碼只是刪除了我的gridview的第一行! 請幫幫我。我使用了Entity Framework和wpf C#。從wpf的數據庫和gridview中刪除一行

using (AccountingEntities cntx = new AccountingEntities()) 
{ 
    Producer item = this.grdProducers.SelectedItem as Producer; 
    cntx.DeleteObject(cntx.Producers.First(x => x.ID == item.ID)); 
    cntx.SaveChanges(); 
    dataPager.Source = cntx.Producers.ToList(); 
} 
+0

您是否有任何要求在刪除選定項目之後選擇第一項作爲選定內容...? – Bathineni

+0

默認刪除第一個項目後選中。我認爲這是gridview的默認行爲。 –

+0

你可能會認爲這是一個LINQ +問題,因爲關鍵代碼是 * cntx.DeleteObject(cntx.Producers.First(x => x.ID == item.ID)* –

回答

0

我找到了解決辦法:當我打開確認刪除操作的對話框中,選擇的項目改變。 我應該在打開對話框之前選擇entityId。下面的代碼顯示瞭如何執行此操作:

  int unitTypeId = (this.grdUnitTypes.SelectedItem as UnitType).ID; 
      ConfirmWindowResult result = Helpers.ShowConfirm(this, SR.GlobalMessages.AreYouSureToDelete, SR.GlobalMessages.Warning); 
      if (result == ConfirmWindowResult.Yes) 
      { 
       using (AccountingEntities cntx = new AccountingEntities()) 
       { 
        try 
        { 
         cntx.UnitTypes.DeleteObject(cntx.UnitTypes.First(x => x.ID == unitTypeId)); 
         cntx.SaveChanges(); 
         dataPager.Source = cntx.UnitTypes.ToList(); 
         MessageBox.Show("Success"); 
        } 
        catch (Exception ex) 
        { 
         MessageBox.Show("Error"); 
        } 
        finally 
        { 
         cntx.Dispose(); 
        } 
       } 
      } 
0

也許你應該簡單的嘗試:

cntx.DeleteObject(cntx.Producers.where(x => x.ID == item.ID)); 

// if you get my .where() code to return the entity's index you'll should be fine 

這應該調用此時,相應的λ/ LINQ。 由於您使用 「where」 的表述被施加到每一個 「生產者」 -entity x匹配item.ID

UPDATE:

從MSDN:

刪除從數據指定的索引處的記錄資源。

DeleteObject(int rowIndex) 

嗯,這解釋了很多。因爲這意味着,你只是傳遞錯誤的論點。 您需要使用foreach循環遍歷整個Grid,或者使用deleteObject刪除每個實體,並檢查對象的id是否與item.ID匹配。

我相信通過使用Lambda/LINQ會更容易,但我目前不知道如何做到這一點。

我也發現這很有趣,你必須向下滾動到「刪除」,這個例子是針對數據庫的,但仍然使用網格作爲緩衝區,所以它應該是類似的問題。

http://www.asp.net-crawler.com/articles/LINQ/Insert-retrieve-update-delete-through-gridview-using-LINQ-to-SQL.aspx

+0

感謝您的回答 - 沒有這個沒有錯誤,但實體不刪除!我真的很累 –

+0

@ mze666真的很奇怪,因爲代碼背後的邏輯應該完全按照你想要的結果做。 –