DataGridView绑定时,不应用DefaultCellStyle格式 [英] DefaultCellStyle format is not applied when DataGridView is bound

查看:171
本文介绍了DataGridView绑定时,不应用DefaultCellStyle格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

此时,表仍为空。所以后来当行被添加到表中并且它很好地反映在DataGridView中时,由于某些原因格式不适用于列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.

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

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

s1给我一个正确的格式,但s2是只是一个空字符串。

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!

推荐答案

尝试在 CellFormatting 事件。

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

这篇关于DataGridView绑定时,不应用DefaultCellStyle格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆