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

前端 未结 5 1473
北荒
北荒 2020-12-16 15:09

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

5条回答
  •  情书的邮戳
    2020-12-16 15:27

    A possible solution if you do want to reuse the formatting provided during the Cellformatting-event (e.g. the cellstyle-elements like fontbold and backgroundcolor). These cellstyles seem to be only available between the 'cellformatting' and 'cellpainting' events but not in the datagridview-cell's style itself..

    Capture the cellstyles during the cellformatting-event with a second handler like this:

    1. in the exportmodule add a shared list, array or dictionary to store the cellstyles:

      Dim oDataGridFormattingDictionary as  Dictionary(Of String, DataGridViewCellStyle) = nothing
      
    2. initialize the dictionary and add a second handler to the datagridview in your printing or export-code. In vb.net something like this:

       oDataGridFormattingDictionary = New Dictionary(Of String, DataGridViewCellStyle)
       AddHandler MyDatagridviewControl.CellFormatting, AddressOf OnPrintDataGridView_CellFormatting
      
    3. Add the code for the handler

      Private Sub OnPrintDataGridView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs)
      If e.RowIndex > -1 AndAlso e.ColumnIndex > -1 AndAlso Not e.CellStyle Is Nothing Then
         If Not oDataGridFormattingDictionary Is Nothing andalso oDataGridFormattingDictionary.ContainsKey(e.RowIndex & "_" & e.ColumnIndex) = False Then
          oDataGridFormattingDictionary.Add(e.RowIndex & "_" & e.ColumnIndex, e.CellStyle)
         End If
      End If
      End Sub
      
    4. Very important: to make sure the original cellformating-event (AND the second cellformatting-handler after that) are actually called you have to request the formattedvalue for each cell that you want to print (e.g.

      oValue = Datagridview.rows(printRowIndex).Cells(printColumnIndex).FormattedValue)
      

      !

    5. When printing you can now check if the cell has formatting. E.g.:

      if not oDataGridFormattingDictionary is nothing andalso oDataGridFormattingDictionary.ContainsKey(printRowIndex & "_" & printColumnIndex) Then
      ... the cellstyle is accesible via:
      oDataGridFormattingDictionary(printRowIndex & "_" & printColumnIndex)
      end if 
      
    6. at the end of the export or printcode remove the handler and set the dictionary to nothing

      RemoveHandler DirectCast(itemToPrint.TheControl, DataGridView).CellFormatting, AddressOf OnPrintDataGridView_CellFormatting
      oDataGridFormattingDictionary = nothing
      

提交回复
热议问题