What is the correct way to change the context when using a DataGridView?

544 views Asked by At

I got totally confused about making these changes.

Lets say that we have a table in the database, lets call it Customers.

We get the data from the table by using the entity framework, like that: List<Customers> customers = context.Customers.ToList();

We also have a BindingSource and we use the List<Customers as a data source: bindingSource1.DataSource = customers;

And in the end, we assign the binding source as a data source of the DataGridView: dataGridView1.DataSource = bindingSource1;

Now lets say that we want to add a new customer. What is the proper way to perform add/change on the data? Should we add/update the List<Customers> and in the end just save the context?

Also in the same time, what is the proper way to cancel the changes? Assuming that we use some of the suggestions mentioned here: How to Refresh DbContext and here: https://code.msdn.microsoft.com/How-to-undo-the-changes-in-00aed3c4

When the changes in the context are cancelled(all modified, deleted and added entries are cancelled), how do we update the DataGridView or the BindingSource?

I think I am missing a piece of the puzzle.

2

There are 2 answers

0
Apostrofix On BEST ANSWER

I've come to the solution and it is to use a two-way data binding. That way all sides will get notified when we add, edit or delete records from the grid. Microsoft have a tutorial here LINK but there are also other ways.

0
MrVoid On

I think that the piece of the puzzle that you are missing is the DataAccess Layer. if you expose the context inside this layer you can define some rules to law your code.

Context->DataAccess Layer->Presentation Layer

In this way you can deal with the context as you want , You can design a method that will return the full table of customer as you have it now:

 List<Customers> customers = context.Customers.ToList(); 

But also you can design a method that will add or modify a single customer to the context and save the changes:

public void UpdateCustomer (Csutomer customer)
{
    using (var ctx = new Context())
    {
        ctx.Customer.ApplyChanges(customer);
        ctx.SaveChanges(); // 
    }            
}

In this last method you can assign a EntityState to the action and using:

 if (entity.EntityState == EntityState.Modified || entity.EntityState == EntityState.Deleted) 
 { 
   context.Refresh(RefreshMode.StoreWins, entity); 
 } 
 else if (entity.EntityState == EntityState.Added) 
 {  
   context.Detach(entity); 
 } 

You can deal with the context refresh.

Now the only thing left , its decide how to fire the refresh your the presentation layer (DataGridView)