I am using .NET 4.0 and I get results from the database in a list like that:
List<Customers> customers = context.Customers().ToList();
Then I assign it to a BindingSource
:
bindingSource1.DataSource = null;
bindingSource1.DataSource = customers;
The bindingSource
is used as a data source to a grid view, where changes can be perfomed - adding new records, editing, deleting.
The problem is when I want to cancel the changes and revert the data in the gridview to the one in the database.
I have the following code that cancels the changes:
private void cancelChanges()
{
// Refresh the modified entries
var objectsModified = context.ObjectStateManager.GetObjectStateEntries(
System.Data.EntityState.Modified | System.Data.EntityState.Deleted)
.Select(e => e.Entity);
context.RefreshFromDb(objectsModified);
// Detach the added entries
var objectsAdded = context.ObjectStateManager.GetObjectStateEntries(
System.Data.EntityState.Added)
.Select(e => e.Entity);
foreach (var item in objectsAdded)
{
context.Customers().Detach(item as Customers);
}
}
I can see that it works, but the problem is that the List still keeps the old records(that should be cancelled) and therefore the binding source too, and in the end they are still displayed in the grid.
Since you're writing from the context into a list, you will only get one-way databinding. To do what you're after, try something like this:
The problem is you are telling the database to discard the changes but since your list is stiill bound to the controls and separate from the database at this point, you can't see the changes reflected. Alternatively, you could call
customers = context.Customers().ToList()
again after you call CancelChanges to re-load current data from the database.