2011-08-17 100 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真的很奇怪,因为代码背后的逻辑应该完全按照你想要的结果做。 –