24

I'm binding list of entities to a data grid view like this:

var orders = context.Order.ToList();

BindingList<Order> orderList = new BindingList<Order>(orders);

dataGridView1.DataSource = orderList;

User can edit or add new directly on datagridview. When user click Save button, in order to optimize performance, I want to retrieve list of entities that has been changed/new to perform insert/update. How can I achieve this?

EDIT Define add new row to gridview:

BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

order.Add(new Order());

EDIT 2 Solve:

BindinList<Order> orders = (BindingList<Order>)dataGridView1.Datasource;

Order order = new Order();

context.Order.Add(order);

order.Add(order);

1 Answer 1

49
List<Object> modifiedOrAddedEntities = context.ChangeTracker.Entries()
 .Where(x => x.State == System.Data.Entity.EntityState.Modified 
        || x.State == System.Data.Entity.EntityState.Added)
 .Select(x=>x.Entity).ToList();

When binding EF entities to a DataGridView it is often preferable to create an IBindingList from the DbSet.Local ObservableCollection. This way you get two way databinding and your new entities are automatically added to the context when adding via BindingSource.Add() or IBindingList.Add(). The simplest way to get this working, once properly bound, is to set DataGridView.AllowUserToAddRows to true and new rows the users enter will be new entities Added to the context.

context.Orders.Load();
BindingList<Order> bindingList = context.Orders.Local.ToBindingList();
BindingSource ordersBindingSource = new BindingSource();
ordersBindingSource.DataSource = bindingList;
dataGridView1.DataSource = ordersBindingSource ;

System.Data.Entity must be referenced to use .ToBindingList() and you must be using EF4.1 or greater.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your quick response. Your code can get list of modified entities but it can't get list of new entities. I provide code that use to add new entities. Can you help me to figured out?
@DoanCuong, see additional answer detail.
Excuse me, but would you please show me how to implement the BindingSource.Add() or IBingdingList.Add()? And one more thing, there are no ToBindingList() function on dbset.local. The only way to do it is using var bindingList = new BindingList<Orders>(context.Orders.Local.ToList());
@DoanCuong, answer updated. It can be more complex than I have shown depending on your entity but with some research you should be able to work it out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.