Mike B. Mike B. - 2 months ago 40
C# Question

Delete DataGrid row (WPF) by clicking Delete key button

I have WPF 4 desktop-based application. In one of the windows of this application, I have DataGrid with data, bonded with SQL Server database (via ADO.NET Entity Framework). In order to manipulate data, I have a delete button, that deletes selected row from DataGrid and call

SaveChanges()
method.

Now I want to add support for keyboard manipulations, e.g. I want to let the user remove the row by selecting and clicking on Delete keyboard button.

If I set
CanUserDeleteRows="True"
in window's XAML, it removes selected row but doesn't make commit to database, in other words, it doesn't call
SaveChanges()
method.

I tried to add keyDown event handler to DataGrid a check
if (e.Key == Key.Delete)
, so run remove method that removes selected row and call
SaveChanges()
method, but it doesn't work.

My question is how can I add keyboard event handler to DataGrid that will let remove selected row and call
SaveChanges()
method or just run my own method, that deals with row removing from DataGrid and make commit to DB.

Of course, if you have any other idea, related to my question, feel free to suggest.

Thanks.

Answer

Have you tried with the PreviewKeyDown event? Something like this

<DataGrid x:Name="dataGrid" PreviewKeyDown="dataGrid_PreviewKeyDown">

private void dataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var dataGrid = (DataGrid)sender;
        // dataGrid.SelectedItems will be deleted...
        //...
    }
}