Deletion of multiple items in a collection bound to a datagridview takes forever

StackOverflow https://stackoverflow.com/questions/806605

  •  03-07-2019
  •  | 
  •  

Question

This is not a question, cause I already answerd it. But it may be helpful to others, too.

Here's what happens:

  1. Create a WinForm with a Datagridview and bind a Subsonic ...Collection with more then 500 objects loaded to it
  2. Add some columns to the datagrid and make at least one autosizemode = fill
  3. Add logic to delete all selected columns (i.e. on keypress -> delete)
  4. Mark all records and delete them

This should take about 30 sec. on a high end pc (and scales up: 1 min for 1000 ...)

Cause:

Everytime you delete a row the collections ListChanged event is fired which causes the datagridview to recalculate the space needed for the autosized column (if someone is interested in the "internals" I attached a call graph.

Was it helpful?

Solution

Solution:

While deleting, disable the ListChangedEvent:

mycollection.RaiseListChangedEvents = false;

// Delete multiple rows
foreach(DataGridViewRow row In dataGridView.SelectedRows) {
   dataGridView.Rows.Remove(row);
}


// After that you can re-enable the event:
mycollection.RaiseListChangedEvents = true;

// But you have to call
mycollection.ResetBindings();
//to let the datagridview perform at least one redraw.

The same task now takes only the blink of an eye

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top