C# 如何获取DataGridView单元格当前字体和样式

C# 如何获取DataGridView单元格当前字体和样式,c#,winforms,datagridview,C#,Winforms,Datagridview,在DataGridView的CellFormatting或CellPaint事件处理程序中,我正在设置单元格的字体(粗体)和颜色(字体和背景) private void DataGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { e.CellStyle.Font = new Font(e.CellStyle.Font, FontStyle.Bold);

在DataGridView的CellFormatting或CellPaint事件处理程序中,我正在设置单元格的字体(粗体)和颜色(字体和背景)

    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
控件的事件在请求格式化的方法期间引发,例如在绘制单元格或获取
FormattedValue
属性时。您更改的
CellStyle
将不会应用于单元格,只用于格式化值和绘制,因此您无法在
cellsformatting
事件之外找到这些样式

源代码:方法是引发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=新的DataGridViewCellFormattingEventArgs(cell.RowIndex、cell.ColumnIndex、,
cell.Value、cell.FormattedValueType、cell.InheritedStyle)

rowindex
columnIndex
是交换的,但在更改后效果很好

似乎
DataGridViewCellFormattingEventArgs.CellStyle
只是临时用于格式化单元格。因此,当覆盖它们时,
DataGridViewCell.Style
保持原样。我不确定从单元格本身获取
CellFormatting
事件中定义的颜色是否容易。可以定义
DataGridViewCell.Style
而不是使用
CellFormatting
事件。