The easy method would be assigning a BindingSource to your DataGridView and a BindingList to your BindingSoure. Set the default cell style format of the column that displays the currency to C2.
If you've done that, any added / changed / removed cell of your currency column will automatically be formatted.
However, if you don't want to use the BindingSource, you'll have to do the formatting yourself. Use events DataGridViewCell.CellValidating and DataGridViewCell.CellFormating.
Let's assume you have a columnCurrency, with a decimal value that should be dislayed in format C2. The DefaultCellFormat is set to C2.
Upon validating the cell, check if the value is really a decimal:
private void OnCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.RowIndex == -1) return;
if (e.ColumnIndex == this.columnValue.Index)
{
decimal value;
e.Cancel = !Decimal.TryParse((string)e.FormattedValue, out value);
}
}
Whenever the cell must be formatted, format the value in e.Value:
private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == this.columnValue.Index)
{
if (e.Value == null)
{ // show the Null value:
e.Value = e.CellStyle.NullValue;
e.FormattingApplied = true;
}
else
{ // because validated I know value is a decimal:
decimal value = Decimal.Parse((string)e.Value);
e.Value = value.ToString(e.CellStyle.Format);
e.FormattingApplied = true;
}
// If desired apply other formatting, like background colouring etc
}
}
If you don't want to use "C2" as currency format, and prefer to use your function FormatCurrency you'll have to create a FormatProvider that uses FormatCurrency to Format and set the FormatProvider of the DefaultCellStyle
private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == this.columnValue.Index)
{
... (check for null value as described above)
else
{
e.Value = String.Format(e.Value, e.CellStyle.FormatProvider);
e.FormattingApplied = true;