DefaultCellStyle format is not applied when DataGridView is bound

一笑奈何 提交于 2019-12-11 06:52:10

问题


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!


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/5658287/defaultcellstyle-format-is-not-applied-when-datagridview-is-bound

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!