C# – DefaultCellStyle format is not applied when DataGridView is bound

ccell-formattingdata-bindingdatagridview

I have a code that binds datagridview to datatable through a binding source:

_bind.DataSource = Table;
lGrid.DataSource = _bind;

In DataBindingComplete event i set the DefaultCellStyle for some columns:

void lGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    if (e.ListChangedType == ListChangedType.Reset)
        lGrid.Columns[0].DefaultCellStyle.Format = "+#,##0;-#,##0;0";
}

At this point the Table is still empty. So later when row is added to the table and it reflects in DataGridView nicely, for some reason the format is not applied to the cell of column 0.

I checked the format inside CellFormatting event:

private void lGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs args)
{
    if (args.ColumnIndex == lGrid.Columns[0].Index)
    {
        string s1 = lGrid.Columns[0].DefaultCellStyle.Format;
        string s2 = lGrid[0, args.RowIndex].Style.Format;
    }
}

and s1 returns me a correct format, but s2 is just an empty string.

Can you please advise what i am doing wrong, and how to get my cell formatted.
Thanks!

Best Answer

Try formatting the cell style in the CellFormatting event.

private void lGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs args) 
{
    if (args.ColumnIndex == 0)
    {
        args.Value = // format Value here
        args.FormattingApplied = true;
    }
}
Related Topic