I ran into this one the other day, and figured I’d share it.
A particular dialog seemed quite slow to update a bunch of data. I did a bit of rough profiling using the .Net Stopwatch class, and narrowed it down to a few key areas that were taking quite a long time. The worst culprit of the bunch: adding new rows to a DataGridView. It was taking somewhere in the neighborhood of 11 seconds to refresh a list of several hundred items in a DataGridView.
After doing a bit more digging I narrowed this down a bit further. One thing that was being done is that the row color was being set after the row was added, like this:
dataGrid.Rows.Add(parameter1, parameter2, parameter3);
dataGrid.Rows[dataGrid.Rows.Count - 1].DefaultCellStyle.BackColor = Color.LightGray;
Create a new DataGridViewRow, and add it to the DataGridView, then set it’s color. Seems simple enough, right? It turns out this is definitely the wrong way to do things, even if it first appeared to be the most obvious. A bit of testing later, and I came up with something that looked like this:
DataGridViewRow row = new DataGridViewRow();
row.SetValues(paramter1, parameter2, parameter3);
row.DefaultCellStyle.BackColor = Color.LightGray;
Doing things this way (creating the new DataGridViewRow, setting it’s color, then adding it to the DataGridView) resulted in a much faster dialog. Much much faster. Rather than the ~11 seconds it was taking before, it was down to ~160 ms.
So, remember kids, if you are wanting to set the row coloring on a DataGridView, do it before you add it to the grid. Setting it afterwards seems to result in redrawing the entire grid which is a lot slower.
(I do realize that using a DataGridView in virtual mode would probably be the better solution, but for the time being, this seems to more than meet the requested needs).