Question Use Accounting format in Datagridview

Runescope

Well-known member
Joined
Jan 6, 2011
Messages
53
Programming Experience
Beginner
Hi!

Just curious if anyone knows if it's possible to format numbers in the DataGridView so they look like the Accounting format in Excel. This is different from the Currency format (which I know how to do).

for example:
$5000.00
$3000.00
$2500.50
_$100.00
That is currency formatting, the dollar sign is right up against the numbers.

$___5000.00
$___3000.00
$___2500.50
$____100.00

That is accounting formatting, the dollar sign is hard left in the cell and the dollar amounts are hard right.

No biggie if it can't be done (or done easily), it's just a little CDO of mine that I would prefer. :)
Thanks!
 
There would be no inbuilt way to accomplish that with the standard DataGridViewTextBoxCell, as far as I'm aware. If you created a custom cell type then you could draw the text yourself and achieve it.
 
Here's an example of that, if you add these classes to project the column can be added directly in Columns editor in designer:
VB.NET:
Public Class AccountingColumn
    Inherits DataGridViewTextBoxColumn

    Public Sub New()
        CellTemplate = New AccountingCell
        DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    End Sub
End Class
VB.NET:
Public Class AccountingCell
    Inherits DataGridViewTextBoxCell

    Protected Overrides Sub Paint(graphics As Graphics, clipBounds As Rectangle, cellBounds As Rectangle, rowIndex As Integer,
                                  cellState As DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String,
                                  cellStyle As DataGridViewCellStyle, advancedBorderStyle As DataGridViewAdvancedBorderStyle,
                                  paintParts As DataGridViewPaintParts)
        MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)

        If value IsNot Nothing Then
            Dim symbol = Globalization.NumberFormatInfo.CurrentInfo.CurrencySymbol
            Dim fcolor = If(Selected, cellStyle.SelectionForeColor, cellStyle.ForeColor)
            Using brush As New SolidBrush(fcolor), format As New StringFormat With {.LineAlignment = StringAlignment.Center}
                graphics.DrawString(symbol, cellStyle.Font, brush, cellBounds, format)
            End Using
        End If
    End Sub
End Class
Perhaps you want to remove the Nothing test, or test for 0/IsDBNull instead, depending on usage.
 
Last edited:
Back
Top