【问题标题】:Entity Framework Can't modify data in datagrid实体框架无法修改数据网格中的数据
【发布时间】:2013-10-18 15:12:06
【问题描述】:

我正在尝试学习实体框架,但我有一些我自己无法解决的问题 我正在将数据从 MS SQL 数据库加载到数据网格并尝试从那里修改/添加数据。 但我不知道如何实现这一点。 这是我的代码:

    using (var context = new OrdersDataModelContainer())
        {
            var customersQuery = from o in context.Payments
                                 select o;
            dataGridView1.DataSource = customersQuery;
        }

当我这样做时,我得到了这个:

当我修改代码时:

    using (var context = new OrdersDataModelContainer())
        {
            var customersQuery = from o in context.Payments
                                 select o;
            dataGridView1.DataSource = customersQuery.ToList();
        }

我的表格看起来:

但是我不能修改数据或添加新行。

谁能通过显示一些代码 sn-p 或指出我可以找到解决方案的地方来帮助我解决这个问题?

谢谢!

@更新 我使用 VS 2012 和 SQL Server 2012(如果重要的话)

【问题讨论】:

  • 为什么不呢?你连Saving code都不用,怎么更新?
  • 好的,但我什至无法更改数据网格单元格中的任何内容

标签: c# winforms entity-framework datagrid


【解决方案1】:

这是因为网格的底层数据源不支持修改。解决方案:

using (var context = new OrdersDataModelContainer())
{
    var customersQuery = from o in context.Payments
                         select o;
    dataGridView1.DataSource = new BindingList<Payments>(customersQuery.ToList());
}

感谢King King的评论

更新: 要保存更改,您需要保留实际跟踪对检索到的实体的修改的上下文,这些实体现在显示在网格中。所以一种方式(也许是最简单的方式)是将上下文声明为表单成员:

public partial class Form1 : Form
{
     private MyDBContext context = new MyDBContext(); // whatever your context name is

     private void btnLoadData_Click(object sender, EventArgs e) // when you want to load the data
     {
        var customersQuery = from o in context.Payments
                             select o;
        dataGridView1.DataSource = new BindingList<Payments>(customersQuery.ToList());
     }

     private void btnSaveChanges_Click(object sender, EventArgs e) // when you want to save
     {  
       context.SaveChanges();
     }
}

注意context不建议长期保存。有很多关于上下文生命周期的文章。

【讨论】:

  • 应该是new BindingList&lt;Payments&gt;(customersQuery.ToList())
  • 谢谢!你能告诉我另一件事我应该在哪里添加 saveChanges() 来记住更改吗?
  • @szpic 要保存更改,您需要保留 context。我会在一分钟内更新答案,向您展示如何操作。
  • @Alireza 谢谢!使用此代码 sn-p 我可以修改数据但不能添加新行。在 Id 上是 identity(1,1) 并且添加的任何行都被省略并且不保存在数据库中。
  • @szpic 这是因为没有通知上下文有关添加的行。您可以在网上搜索以找到解决方案,因为有很多方法可以做到这一点。一种方法是搜索网格以查找 Id=0 的行。另一种方法是处理 UserAddedRow 事件并保留添加行的索引。更好的方法是使用 BindingSource。那里有一些教程。
猜你喜欢
  • 2023-03-06
  • 2014-04-19
  • 1970-01-01
  • 2013-08-17
  • 2016-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
相关资源
最近更新 更多