Search code examples
c#wpfdatagriddatatablerowdeleting

Fire only one event after deleting multiple DataTable rows


I have a DataTable with many rows, and the DataTable is bound to a DataGrid. After deleting one or more rows via the DataGrid, I need to run specific, quite complex checks on the remaning rows.

I subscribe to the RowDeleted event, and call the checking method from there. My problem is, when deleting multiple rows via the DataGrid, the RowDeleted event is fired for every single row, calling the checking method every time. As the checking method checks all the remaining rows and all their columns, it is a big slowdown for my application, also very redundant. It would be enough to run it once all the selected rows are deleted.

Is there a way to fire only one event after deleting any number of rows?


Solution

  • You could do this with the help of a timer. Declare a global timer and set its properties:

    System.Timers.Timer _delayTimer = new System.Timers.Timer(1000);
    _delayTimer.Elapsed += new EventHandler(_delayTimer_Elapsed);
    
     void _delayTimer_Elapsed(object sender, EventArgs e)
     {
         _delayTimer.Stop();
         Dispatcher.Invoke(new Action(UpdateMethodName)); 
         //or - with passing arguments:
         Dispatcher.Invoke(new Action<string>(UpdateMethodName), new object[]{"argument"});
     }
    

    Now in your RowDeleted-Event, you do this:

    _delayTimer.Stop();
    _delayTimer.Start();
    

    Because the timer gets restarted in the RowDeleted-event over and over again, your update logic will only get called after the last handler is fired.