在datagridview的单元格式或单元格事件处理程序中,我要设置单元格的字体(要大胆)和颜色(前台和背景)。
private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
e.CellStyle.ForeColor = Color.White;
e.CellStyle.BackColor = Color.Black;
}
private void DataGrid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);
e.CellStyle.ForeColor = Color.White;
e.CellStyle.BackColor = Color.Black;
}
这是按预期工作的,所需的字体和颜色也适当显示。后来,我试图阅读单元格中的字体和颜色,但它们似乎是空的。
foreach (DataGridViewRow dgvr in dataGrid.Rows)
{
Font font = dgvr.Cells[0].Style.Font;
Color foreColor = dgvr.Cells[0].Style.ForeColor;
Color backColor = dgvr.Cells[0].Style.BackColor;
}
字体始终为空,颜色为空。
它们存储在哪里,我该如何访问它们?
CellFormatting
DataGridView
控件的事件是在要求格式化的方法中提高的,例如在绘画单元格或获得FormattedValue
属性时。您更改的CellStyle
将不适用于单元格,而仅用于格式化值和绘画,因此您找不到CellFormatting
事件之外的这些样式。
源代码: DataGridViewCell.GetFormattedValue
方法是引起CellFormatting
事件的中心方法,如果您查看该方法的源代码,您可以看到您在CellStyle
上使用的更改不是存储在单元格中。
解决方案
作为解决问题的选项,您可以在需要时自己提出CellFormatting
事件,并使用格式化的结果。为此,您可以为DataGridViewCell
创建这种扩展方法:
using System;
using System.Windows.Forms;
using System.Reflection;
public static class DataGridViewColumnExtensions
{
public static DataGridViewCellStyle GetFormattedStyle(this DataGridViewCell cell) {
var dgv = cell.DataGridView;
if (dgv == null)
return cell.InheritedStyle;
var e = new DataGridViewCellFormattingEventArgs(cell.RowIndex, cell.ColumnIndex,
cell.Value, cell.FormattedValueType, cell.InheritedStyle);
var m = dgv.GetType().GetMethod("OnCellFormatting",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new Type[] { typeof(DataGridViewCellFormattingEventArgs) },
null);
m.Invoke(dgv, new object[] { e });
return e.CellStyle;
}
}
然后您可以这样使用该方法:
var s = dataGridView1.Rows[].Cells[0].GetFormattedStyle();
var f = s.Font;
var c = s.BackColor;
var e = new DataGridViewCellFormattingEventArgs(cell.RowIndex, cell.ColumnIndex,
cell.Value, cell.FormattedValueType, cell.InheritedStyle)
rowindex
和 columnIndex
已交换,但是更改后效果很好