【问题标题】:How to get DataGridView Cell current font and style如何获取 DataGridView Cell 当前字体和样式
【发布时间】:2017-07-30 09:37:24
【问题描述】:

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

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

字体始终为空,颜色为空。

它们存储在哪里以及如何访问它们?

【问题讨论】:

  • 看来DataGridViewCellFormattingEventArgs.CellStyle只是临时用来格式化单元格的。因此,当您覆盖它们时,DataGridViewCell.Style 将保持原样。我不确定是否可以轻松地从单元格本身获取CellFormatting 事件中定义的颜色。也许定义 DataGridViewCell.Style 而不是使用 CellFormatting 事件。

标签: c# winforms datagridview


【解决方案1】:

DataGridView 控件的CellFormatting 事件在请求格式化的方法期间引发,例如在绘制单元格或获取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;

【讨论】:

    【解决方案2】:
    var e = new DataGridViewCellFormattingEventArgs(cell.RowIndex, cell.ColumnIndex,
                cell.Value, cell.FormattedValueType, cell.InheritedStyle)
    

    rowindexcolumnIndex 已交换,但更改后效果很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多