I have a DataGridView (DGV) that I'm populating manually (not bound to a datasource). It's relatively small (12 columns x 62 rows). When my form loads, it populates each cell with data from various sources, and applies style changes to some of the cells, such as fore color, background color, and possibly font change.
Everything is going great except for the style changes. I did some tests using Stopwatches, and the formatting is taking roughly 2X longer than all of the processing that goes into populating the form. My computations are fairly intensive, whereas I would think applying formatting would be almost instantaneous, so I'm baffled why applying some style changes is taking twice as long as my intense computations.
I've already taken some measures to reduce the time quite a bit, such as turning on double-buffering as well as suspending drawing for my DGV before my formatting begins and resuming it after. These helped a lot, and also eliminated the flicker that was happening as each cell of my DGV was repainted. As far as I can tell, doing these two things helped combine the actual painting of the style changes into a single paint operation. So a rough outline of the loading of my form goes like this:
- Form load begin
- "SuspendDrawing" for DGV
- Populate DGV with data
- Apply style changes to each cell
- "ResumeDrawing" for DGV and Refresh (Redraw) DGV.
To clarify, Step 4 is made up only of lines like the following:
myCell.Style = New DataGridViewStyle()
myCell.Style.BackColor = ...
myCell.Style.ForeColor = ...
myCell.Style.Font = New Font()
In all those steps, it's Step 4 that takes the most time. Even Step 5 is nearly instantaneous. This doesn't make sense to me. Drawing is suspended when Step 4 takes place, so there should be no graphics computations or painting taking place. It should purely be storing those Style changes for each cell.
So, why is applying cell style changes so slow, and what can I do to speed it up other than what I already have?
Update 2/5/20
I've been asked to provide reproducible code. I'll need to take some time to put together a MWE. In the meantime, hopefully this will help: after populating my table (step 3 above), I apply cell styles in Step 4 something like this:
For Each row As DataGridViewRow In myDGV.Rows
For Each cell As DataGridViewCell In row.Cells
Select Case [somecondition]
Case X
cell.Style = New DataGridViewStyle()
cell.Style.BackColor = Colors.White
cell.Style.ForeColor = Colors.Black
cell.Style.Font = New Font(DefaultFont, FontStyle.Italic)
Case Y
[similar]
Case ...
End Select
Next
Next