在wpf中删除数据库和gridview中的行

时间:2011-08-17 13:39:04

标签: c# wpf entity-framework gridview

我想从gridview和数据库中删除一行 - 我写了一些代码,但这段代码只删除了gridview的第一行! 请帮我。我使用了Entity Framework和wpf C#。

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();
}

2 个答案:

答案 0 :(得分: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

这应该调用适当的lambda / linq。 由于您使用“where”,因此表达式将应用于匹配x的每个“生产者”-Entity item.ID

更新:

来自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

答案 1 :(得分: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();
                    }
                }
            }
相关问题