在wpf中从数据库和gridview中删除一行

本文关键字:一行 删除 gridview wpf 数据库 | 更新日期: 2023-09-27 18:05:57

我想从gridview和数据库中删除一行-我写了一些代码,但这段代码只是删除我的gridview的第一行!请帮帮我。我使用了实体框架和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();
}

在wpf中从数据库和gridview中删除一行

我找到了解决方案:当我打开确认删除操作的对话框时,选中的项目发生了变化。在打开对话框之前,我应该选择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();
                    }
                }
            }

也许你应该试试:

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",因此表达式应用于与item.ID匹配的每个"生产者"-实体x

更新:

来自MSDN:

从数据源删除指定索引处的记录。

DeleteObject(int rowIndex)

这就解释了很多。因为这意味着,你只是传递了错误的参数。您需要使用foreach或for循环遍历整个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