【问题标题】:DefaultCellStyle format is not applied when DataGridView is bound绑定 DataGridView 时不应用 DefaultCellStyle 格式
【发布时间】:2011-04-14 03:43:58
【问题描述】:

我有一个通过绑定源将datagridview绑定到数据表的代码:

_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 只是一个空字符串。

您能否告知我做错了什么,以及如何格式化我的单元格。 谢谢!

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 我尝试在 CellFormatting 中设置 lGrid[0, args.RowIndex].Style.Format = "+#,##0;-#,##0;0" 但它不起作用
    • @jfs 是的,肯定适用于未绑定到任何表并直接更新的数据网格。
    • @jfs 感谢您的想法,不幸的是那没有用。事实上,当我在赋值 args.CellStyle.Format = "+#,##0;-#,##0;0" 之前检查 args.CellStyle.Format 时,它实际上已经等于它了。但仍然没有显示在 DataGridView 上。
    • @Anya 你能粘贴更新的代码吗? args.Value格式化后的值是多少?
    【解决方案2】:

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

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

    1. 当创建带有列的 DataTable 时

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

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

    【讨论】:

    • 这是我的问题。但我正在使用设计器,将 dgv 绑定到数据源。所以只需在设计器中转到数据集的 DataTable,选择列,然后在属性窗口中,将数据类型设置为 System.Double
    猜你喜欢
    • 2021-07-16
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多