c# - 绑定(bind) DataGridView 时不应用 DefaultCellStyle 格式

标签 c# data-binding datagridview cell-formatting

我有一个通过绑定(bind)源将 datagridview 绑定(bind)到 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";
}

此时表格仍然是空的。因此,稍后当行被添加到表中并且它很好地反射(reflect)在 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 只是一个空字符串。

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

最佳答案

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

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

关于c# - 绑定(bind) DataGridView 时不应用 DefaultCellStyle 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5658287/

相关文章:

c# - 将字符串转换为 long 类型并在 asp.net MVC 中的 linq 查询中使用

c# - 是否可以将 [XmlAttribute] 作为类的默认值?

c# - 我应该通过绑定(bind)使用 MVP 和 WPF 显示数据吗?

c# - 为什么 Visual Studio 会自动更改窗体的布局?

c# - WinForm 中的 DataGridView 自定义排序

c# - 在 C# 中获取 FTP 上的文件大小

不可序列化对象上的 C# DoDragDrop

c# - 如何将数据绑定(bind)到控件的 Visibility 属性

wpf - 如何调试 Windows 运行时数据绑定(bind)?

c# - BindingSource 取消 AddingNew