Click here to Skip to main content
15,891,607 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to format a single cell. I have a unbound datagridview and I want to format the current cell as currency.

C#
DataGridView1.CurrentCell.Style.Format = "c"

DataGridView1.Item(2, 2).Style.Format = "c"


neither of these instructions work. Is there anyway I can do this?
Posted

Try this code let me know if it works.

VB
Private Sub DGVStocksMaster_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DGVStocksMaster.CellFormatting
    If Not IsNothing(e.Value) Then
        If e.ColumnIndex().ToString = 6 And IsNumeric(e.Value) Then
            e.Value = Format(FormatCurrency(e.Value)) ', e.CellStyle.Format)
        End If
    End If
End Sub
 
Share this answer
 
The cell formatting does not apply to the existing value, it will change on subsequent value changes automatically. I have come up with this;

VB
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click

    For Each cell As DataGridViewCell In DataGridView1.SelectedCells
        cell.ValueType = GetType(System.Single)
        Dim newStyle As New DataGridViewCellStyle
        newStyle.Format = "C"
        cell.Style.ApplyStyle(newStyle)
    Next

End Sub

Private Sub DataGridView1_CellFormatting(sender As Object, e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If Not IsNothing(e.Value) Then
        If IsNumeric(e.Value) Then
            e.Value = Format(CDbl(e.Value), e.CellStyle.Format)
        End If
    End If
End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900