Is there a way to force a DataGridView to fire its CellFormatting event for all cells?

hawbsl picture hawbsl · May 18, 2012 · Viewed 12.7k times · Source

We use the CellFormatting event to colour code cells in various grids all over our application.

We've got some generic code which handles export to Excel (and print) but it does it in Black & White. Now we want to change this and pick up the colour from the grids.

This question & answer has helped (and it works) ... except there's a problem with larger grids that extend beyond a single screen. The portions of the grid which haven't yet been displayed on screen are (logically) never getting their CellFormatting code fired, and so their underlying colour never gets set. As a result, in Excel, the colour coding fizzles out half way down the page.

Seems there are three solutions:

1) Tell the user he has to scroll to all parts of the grid before doing an Export to Excel. Ha! Not a serious solution

2) Programmatically scroll to all parts of the grid before doing an Export to Excel. Only slighly less horrible than (1)

3) In our Export to Excel code, fire something at the top which tells the DataGridView to paint/format its entire area e.g.

  MyDataGridView.FormatAllCells()

Is there something that does something like this???

Oh, and there is a fourth option but this will involve touching a massive amount of existing code:

4) Stop using CellFormatting event, format the cells at load time. Problem with this is we'd have to retool every grid in our application since CellFormatting is the way we've done it since year dot.

Answer

Rex Schrader picture Rex Schrader · May 27, 2012

I have a possible solution - In your export function access the Cell.FormattedValue property of each cell. According to Microsoft, this forces the CellFormatting event to fire.