【问题标题】:How do I get a Windows Forms DataGridView to show new records when bound to EntityCollection绑定到 EntityCollection 时如何让 Windows 窗体 DataGridView 显示新记录
【发布时间】:2011-06-14 02:16:05
【问题描述】:

尝试在运行时向 EntityCollection 添加新记录,并使用新信息更新 DataGridView。

我尝试将 datagridview 直接绑定到实体集合(即 ObjectSet),并通过绑定到同一集合的 BindingSource。

我已经尝试过 DataGridView.Refresh()、DataGridView.EndEdit() 和 BindSource.ResetBindings() 等,但似乎没有任何效果。

【问题讨论】:

    标签: .net winforms datagridview entitycollection


    【解决方案1】:

    试试看:

    bindingSource.DataSource = null;
    bindingSource.DataSource = theCollection;
    

    或者,您可以在BindingList<T> 中维护数据的内存副本。将DataGridView绑定到BindingList,当你在ObjectSet添加实体时,也将其添加到BindingList

    【讨论】:

    • 又名贫民区的方式,:)。希望有一种不那么蛮力的方法。这不起作用,因为我目前绑定到 BindingSource。这会导致网格被清除。
    • 实体不能与 DataGridView 一起工作吗?所以我需要保留 2 个相同数据的集合才能使其正常工作?
    • @Jaime,您需要意识到 ObjectSet 并不是真正的集合,它实际上是一个查询。它不会将实体保留在内存中(尽管 ObjectContext 保留了已加载实体的缓存)
    • 是的,我明白了。我想我认为实体人员会提出解决方案或推荐与实体进行数据绑定的方法。表单中数据绑定的全部意义在于简化事情,而不是让它变得更难。
    • Entity Framework 并不是专门为数据绑定而设计的……您可以在控制台应用程序或 ASP.NET 网站中使用它。 EF 没有理由关心数据绑定...
    【解决方案2】:

    我遇到了同样的问题。微软应该关心使用他们技术的人,而 EF 应该关心数据绑定。 Jaime,如果您找到更好的方法,请更新此列表。对我来说,重新创建上下文实例对我来说很好。有趣的是调试器显示实体上下文和绑定源有最新更新,但 datagridview 仍然没有刷新。谢谢

    Here 是迄今为止我找到的最佳解决方案 -

    基本上你需要做的

    bindingSource.DataSource = EntityContext.Collection
                                   .Execute(MergeOption.AppendOnly);
    

    【讨论】:

      【解决方案3】:

      我希望现在还不算太晚 =) 我有一些东西在这里有用...

      // Entity Data Model
      private ManagerEntities context = new ManagerEntities();
      
      // declare private member    
      private BindingList<Currency> lstCurrencies = null;
      
      // on form load, load data and bind to DataGridView's DataSource
      
      private void Form1_Load(object sender, EventArgs e) {
      
           lstCurrencies = new BindingList<Currency>();
      
           ObjectResult or = ((ObjectQuery)currencies).Execute(MergeOption.AppendOnly);
           foreach (Currency c in or)
               lstCurrencies.Add(c);
      
           // dgMain is my DataGridView
           dgMain.DataSource = lstCurrencies;
      }
      
      // this will save objects that have changed. You might want to add logic for newly created and deleted objects.
      private void btnSave_Click(object sender, EventArgs e) {
          context.SaveChanges();
      }
      

      【讨论】:

        猜你喜欢
        • 2010-10-13
        • 1970-01-01
        • 2015-05-22
        • 1970-01-01
        • 2016-05-23
        • 2010-11-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多