首页 > 解决方案 > 特定 dataGridView 行中的粗体字体

问题描述

我正在寻找并尝试不同的解决方案来解决我的问题,但它们都不起作用。如果具有特定索引的单元格具有特定值,我需要在一行中的所有单元格中设置粗体。我究竟做错了什么?

foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        if (row.Cells[14].Value.ToString() == "Yes")
                        {
                            row.DefaultCellStyle.Font = new Font(dataGridView1.Font, FontStyle.Bold);
                        }
                    }

编辑:对不起,这是我的错。条件语句一直检查错误的单元格并且我的代码运行良好。

标签: c#winformsdatagridviewfonts

解决方案


因此,如果 DataGridViewCell 具有某个值,您希望该值以某种字体打印。

用于显示 DataGridViewCell 值的字体位于单元格的 DataGridViewCellStyle 中。

所以我们可以使您的要求更通用:如果 DataGridViewCell 具有某个值,您希望该单元格使用某个 DataGridViewCellStyle 来显示其值。

您可以使用两种方法:

  • 每当单元格改变值时,如果它得到“某个值”,就给这个单元格一个特殊的样式,每当它改变到另一个值时,让它使用默认样式。
  • 每当必须格式化单元格的值时,格式化单元格。

对我来说,第一种方法似乎是最简单的方法。大多数单元格不会经常更改值,因此在我看来,仅在值更改时才这样做更有效,而不是每次都必须格式化单元格的值。

关于 DataGridViewCellStyles

DataGridViewCell 可以具有 DataGridViewCellStyle。如果单元格有样式,则使用此样式。如果它没有样式(值等于 null),则使用 DataGridViewColumn 的 DefaultCellStyle。如果该列也没有样式,则使用 DataGridView.DefaultCellStyle。要让 Cell 或 Column 使用父单元格样式,只需将 (Default)CellStyle 设为 null。实际使用的样式,检查完CellStyle,列的单元格样式等在DataGridViewCell.InheritedStyle

因此,如果您希望某个单元格使用非默认 DataGridViewCellStyle,只需分配您想要的单元格样式。如果您想再次为该列使用默认单元格样式,只需指定 null。

每当值更改时更改单元格样式

const string specialDisplayValue = "yes";
IEqualityComparer<string> cellTextcomparer = StringComparer.CurrentCultureIgnoreCase;

void OnCellValueChanged(DataGridViewCell cell)
{
    string displayedCellValue = this.GetDisplayedValue(cell);
    if (cellTextComparer.Equals(displayedCellValue, specialDisplayValue))
    {
         // special text shown, use special style with special font:
         cell.Style = new DataGridViewCellStyle(cell.Column.InheritedStyle);
         cell.Style.Font = new Font(cell.Style.Font, FontStyle.Bold);
    }
    else
    {
         // other value, use the default style:
         cell.Style = null; // the style from the column will be used.
    }
}

如果 Columns 的 InheritedStyles 不会改变,请考虑在构造函数中只定义一次特殊样式。然后你只需要决定是分配null还是特殊样式。如果所有列都使用相同的样式,您只需使用一种特殊样式,使用 DataGridView.CellStyle 作为模板创建。

自己格式化单元格

使用事件:

dataGridView1.CellFormatting += dataGridView1_CellFormatting;

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    string displayValue = e.Value.ToString();
    if (cellTextComparer.Equals(displayValue, specialDisplayValue))
    {
        // special value, special font
        e.CellStyle.Font = new Fone(e.CellStyle.Font, FontStyle.Bold);
    }
    // else: different value, don't change the font
}

注意:每次必须格式化单元格时都会调用此方法,即使单元格的值没有更改也是如此。因此效率较低。


推荐阅读