Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

How can I add keyboard event handler to DataGrid?

The purpose to be able removing selected row and calling SaveChanges() method or just running my own method, that deals with row removing from DataGrid and making commit to DB.

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

like image 377
Mike Avatar asked Dec 13 '22 18:12

Mike


1 Answers

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...
        //...
    }
}
like image 117
Fredrik Hedblad Avatar answered Dec 28 '22 08:12

Fredrik Hedblad