绑定DataGridView时不应用DefaultCellStyle格式

时间:2011-04-14 03:43:59

标签: c# data-binding datagridview cell-formatting

我有一个代码,通过绑定源将datagridview绑定到datatable:

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

在DataBindingComplete事件中,我为某些列设置了DefaultCellStyle:

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

此时表仍为空。所以稍后当行添加到表中并且它很好地反映在DataGridView中时,由于某种原因,格式不会应用于列0的单元格。

我检查了CellFormatting事件中的格式:

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

和s1返回正确的格式,但s2只是一个空字符串。

你能告诉我我做错了什么,以及如何格式化我的格式。 谢谢!

2 个答案:

答案 0 :(得分:4)

尝试在CellFormatting事件中格式化单元格样式。

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

答案 1 :(得分:1)

这可能是由DataTable Columns数据类型设置为字符串(默认情况下)。

因此,您可以将DataTable Columns数据类型更改为numeric:

  1. 使用列

    创建DataTable时
    Table.Columns.Add(ColumnName,typeof(double));
    
  2. 稍后更改日期类型

    Table.Columns[0].DataType = typeof(decimal);
    
相关问题