I've a little problem using a DataGridView with AllowUserToAddRows set to True that is binding to a list (BindingList<State>).
When adding a new row through the GUI, the row isn't added to the BindingList.
I've a entity which contains a collection with other entities. For example: Country contains States. So, the new row in datagridview isn't added in the StateCollection on country object.
That's is how I add the BindingList to the DataGridView:
var bl = new BindingList<State>(country.StatesCollection.ToList<State>());
grdData.DataSource = bl;
Properties:
EditMode is set to EditOnKeystrokeOrF2
If more data is needed, please ask me.
Following your code, I initialized
context.MyEntitieswith 3MyEntityobjects.After binding, the
DataGridViewshows the 3 rows as well as the expected* NewRow. Thus:After entering data into the
NewRowwithin the GUI, theDataGridViewnow shows 4 rows as well as the expected* NewRow. Thus:Adding an item to the
DataGridViewdid indeed add the object to theBindingListsource, but not to the actualcontext.MyEntitiessource, which I assume is where you are expecting to see this new item added.The reason you are seeing this behavior is because of this line:
You are declaring a new object for your binding. Even if
context.MyEntitiesis also aBindingList<MyEntity>(I doubt since that would negate the reason for the above line of code), it will not be updated with the new entry. For the desired behavior, you have two options:Change
context.MyEntitiestype toBindingList<MyEntity>, then simply change your binding to:Handle
DataGridView.RowsAddedand manually updatecontext.MyEntitiesby a) adding the new item or b) refreshing the original object: