How to trap delete row ( from keyboard ) in datagridview?
Background I have a custom collection that is binded to the datagridview
this.datagridview.DataSource = mycollection
I have a delete button on the user interface . User can click on the delete button to delete the selected DX Directory.
Some entried cannot be deleted so I Enable and Disable "delete button".
It works fine in case开发者_如何转开发 user user deletes entry by clicking the delete butoon.
The problem is :
When user pressed the "delete" button from the "keyboard"
How can trap key board "Delete" button.. When I press delete button from the keyboard:
--it deletes a selected row from the datagrid view.. --When user click save .. it also saves it into Xml as well..
To correct this I have handled _RowRemoved event of datagrid view.. but still no help
Please Help
Attach to the UserDeletingRow event, and cancel the deletion (when required) by setting e.Cancelled = true
since you have a button that handles when they can 'delete' you can just set:
CanUserDeleteRows="false"
right in the DataGrid in the XAML.
this only prevents them from using the "delete" key (your button still works), so it forces them to delete with your button.
If you want them to be able to also use the "delete" key (when appropriate), you will need to attach the UserDeletingRow event and handle the cancel when it isn't appropriate to delete.
I didn't find "UserDeletingRow"-event from the recent versions (using vs2022), so as a workaround, when CanUserDeleteRows is true, handle Delete key in datagrid previewkeydown:
private void GridRecent_PreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Delete:
e.Handled = true;
Console.WriteLine("Cancelled delete");
break;
default:
break;
}
}
精彩评论