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.MyEntities
with 3MyEntity
objects.After binding, the
DataGridView
shows the 3 rows as well as the expected* NewRow
. Thus:After entering data into the
NewRow
within the GUI, theDataGridView
now shows 4 rows as well as the expected* NewRow
. Thus:Adding an item to the
DataGridView
did indeed add the object to theBindingList
source, but not to the actualcontext.MyEntities
source, 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.MyEntities
is 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.MyEntities
type toBindingList<MyEntity>
, then simply change your binding to:Handle
DataGridView.RowsAdded
and manually updatecontext.MyEntities
by a) adding the new item or b) refreshing the original object: