In a Windows Forms MDI Application .net 4.0 with Entity Framework 4.4 I have the following strange behaviour:
In a MDI-Child-Form is a datagridview
databinding:
private void DGUser_gridBind()
{
_users = _frmmaster.DataAdmin.RepositoryAdmin.GetAll<User>();
DGUser.DataSource = _users;
}
The binding is using the context of the master form.
I want that the user can delete an entity either by clicking a delete button or by the del-key.
del-key
private void DGUser_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { if(DGUser.SelectedRows.Count==1) { User selectedUser = (User)DGUser.SelectedRows[0].DataBoundItem; deleteUser(selectedUser); } } }
delete-button
private void btDeleteUser_Click(object sender, EventArgs e) { if (DGUser.SelectedRows.Count == 1) { User selectedUser = (User)DGUser.SelectedRows[0].DataBoundItem; deleteUser(selectedUser); } }
delete Function
private void deleteUser(User user) { _frmmaster.DataAdmin.RepositoryAdmin.Delete<User>(user); _frmmaster.DataAdmin.RepositoryAdmin.UnitOfWork.SaveChanges(); DGUser_gridBind(); }
When I delete a user by clicking the delete-button it works as expected but when I delete a user by using the del-key the selected entity will be deleted, which is fine, but also the first entity in the datagridview will be deleted (the first entity in the dgv is only deleted in the Repository, not in the database, the selected entity is also deleted in the database). When I set a breakpoint in the delete-function of the repository it is only activated one time with the correct entity.
I cannot find out why the first entity in the dgv is also deleted. Both functions are using the same delete function but the result is different. Can anybody give me a hint where to look for my mistake.
By default, when you hit the delete key when a
DataGridView
is focused, it removes the row from theDataGridView
and from the bound collection. However, you're handling theKeyDown
event yourself, removing the row, and updatingDGUser.DataSource
before the default action even occurs. Here's the order of actions (I think):deleteUser
removes selected row from databaseDGUser
is rebound and updatedDgUser
handles default delete key action (possibly on KeyUp?) and removes selected row, which is apparently now the first row after rebindingSolution options
DGUser.AllowUserToDeleteRows = false
since you're handling it yourself anyway, or...DGUser_KeyDown
, handle theDGUser.UserDeletingRow
event, and calldeleteUser
thereI'd probably prefer the second one.