tags:

views:

4829

answers:

3

I want to enable the user to highlight a row on the WPF DataGrid and press delete key to delete the row.

  • the functionality is already built into the UI of the grid, so to the user, the row disappears
  • I currently handle this on the SelectionChanged event (code below)
  • I loop through all the "e.RemovedItems" and delete them with LINQ

Problem is: even when you simply select a row and move off of it, selection change is fired and that row is in e.RemovedItems (which is odd, why would simply selecting something put it in a RemovedItems container?).

So I am looking for a DeleteKeyPressed event so I can simply handle it. What is that event called?

I am using the March 2009 toolkit.

XAML:

<Grid DockPanel.Dock="Bottom">
    <toolkit:DataGrid x:Name="TheDataGrid" 
                      SelectionChanged="TheDataGrid_SelectionChanged"
                      AutoGenerateColumns="True"
                      RowEditEnding="TheDataGrid_RowEditEnding"/>

code-behind:

private void TheDataGrid_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.RemovedItems.Count > 0)
    {
        Message.Text = "The following were removed: ";
        foreach (object obj in e.RemovedItems)
        {
            Customer customer = obj as Customer;
            Message.Text += customer.ContactName + ",";
            _db.Order_Details.DeleteAllOnSubmit(
                customer.Orders.SelectMany(o => o.Order_Details));
            _db.Orders.DeleteAllOnSubmit(customer.Orders);
            _db.Customers.DeleteOnSubmit(customer);
        } 
    }

    try
    {
        _db.SubmitChanges();
    }
    catch (Exception ex)
    {
        Message.Text = ex.Message;
    }
}


ANSWER:

Thanks lnferis, that was exactly what I was looking for, here is my finished delete handling event for the datagrid, note the KeyDown event doesn't fire for some reason.

XAML:

<toolkit:DataGrid x:Name="TheDataGrid" 
                  KeyDown="TheDataGrid_KeyDown"
                  PreviewKeyDown="TheDataGrid_PreviewKeyDown"
                  AutoGenerateColumns="True"
                  RowEditEnding="TheDataGrid_RowEditEnding"/>

code-behind

private void TheDataGrid_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Delete)
    {
        var grid = (DataGrid)sender;

        if (grid.SelectedItems.Count > 0)
        {
            string checkMessage = "The following will be removed: ";

            foreach (var row in grid.SelectedItems)
            {
                Customer customer = row as Customer;
                checkMessage += customer.ContactName + ",";
            }
            checkMessage = Regex.Replace(checkMessage, ",$", "");

            var result = MessageBox.Show(checkMessage, "Delete", MessageBoxButton.OKCancel);
            if (result == MessageBoxResult.OK)
            {
                foreach (var row in grid.SelectedItems)
                {
                    Customer customer = row as Customer;
                    _db.Order_Details.DeleteAllOnSubmit(
                        customer.Orders.SelectMany(o => o.Order_Details));
                    _db.Orders.DeleteAllOnSubmit(customer.Orders);
                    _db.Customers.DeleteOnSubmit(customer);
                }
                _db.SubmitChanges();
            }
            else
            {
                foreach (var row in grid.SelectedItems)
                {
                    Customer customer = row as Customer;
                    LoadData();
                    _db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, customer); //TODO: this doesn't refresh the datagrid like the other instance in this code
                }
            }
        }
    }
}

private void TheDataGrid_KeyDown(object sender, KeyEventArgs e)
{
    Console.WriteLine("never gets here for some reason");
}
A: 

You want to handle the KeyUp or KeyDown event and check the pressed Key for Delete.

private void OnKeyDown(object sender, KeyEventArgs e) {
  if ( Key.Delete == e.Key ) {
    // Delete pressed
  }
}
JaredPar
the KeyDown event doesn't fire when I press a key down (odd), PreviewKeyDown works though
Edward Tanguay
+3  A: 

The RemovedItems items reflects the items removed from the selection, and not from the grid.

Handle the PreviewKeyDown event, and use the SelectedItems property to delete the selected rows there:

private void PreviewKeyDownHandler(object sender, KeyEventArgs e) {
    var grid = (DataGrid)sender;
    if ( Key.Delete == e.Key ) {
        foreach (var row in grid.SelectedItems) {
            ... // perform linq stuff to delete here
        }
    }
}
Inferis
+3  A: 

What are you binding your DataGrid to? Ideally, you should react to CollectionChanged events on the collection you are binding to. That way, your logic (deletion of removed items) will be separated from your UI.

You can build an Observable collection containing your objects and bind it to ItemsSource just for that purpose if the original collection does not have the necessary events.

It might not suit your specific setup, but that's how I usually do it.

Denis Troller
I totally agree with this approach. An ObservableCollection allows your ViewModel to handle any changes to the underlying databound source. You don't have to rely upon code-behind... nothing grossly wrong with getting it done via code-behind... just cleaner using the ViewModel.
Mike L