开发者

DefaultCellStyle format is not applied when DataGridView is bound

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!


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;
    }
}


This may caused by DataTable Columns datatype is set to string(by default).

So you can change the DataTable Columns datatype to numeric:

  1. When create the DataTable with columns

    Table.Columns.Add(ColumnName,typeof(double));
    
  2. Change the date type later

    Table.Columns[0].DataType = typeof(decimal);
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜