1

I've set up a bound dgv to entity using dbcontext. Works fine. The rows are displayed in the dgv and I can modify cells and update using SaveChanges. However, if I attempt to add a new row in the dgv it doesn't get saved. If the dgv is bound to the entity shouldn't the new row get added automatically or do I have to do something to add it? What? Please provide example code. I'm going to try deleting from the dgv next. Will I have a similar problem? How might I get that to work? I scoured the internet for examples but they stop at binding the enitities and don't include addition or deletions. Any help would be appreciated.

user1626137
  • 233
  • 1
  • 3
  • 10

2 Answers2

0

I found a couple of links with a similar problem one of which is:

DataGridView AllowUserToAddRow property doesn't work

It seems that using .ToList messes up the binding. In my case I was using MyContext.MyTable.Local.ToList as the source. When I removed the .ToList everything works perfectly. Perhaps someone can tell us in more detail why this works???

Thanks to those of you that found this first.

Community
  • 1
  • 1
user1626137
  • 233
  • 1
  • 3
  • 10
0

Solution for .NET Framework 4

I have tried Removing the .ToList() but then I simply get no results.

So my workaround was:

For deletes:
On the datagridview UserDeletingRow Event

// Get deleted entity:
myEntityType currentEntity = (myEntityType)BindingSource[e.Row.Index];

// Delete directly from context
context.myEntityType.Remove(currentEntity);

For inserts:
On the save button I loop through the BindingSource and check if any enitity has an ID == 0 and then ADD each of those with context.MyEntityType.Add(currentEntity);

LarsTech
  • 80,625
  • 14
  • 153
  • 225