我有一个通过绑定(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/