DataGridView 只调用 CellFormatting 一次

DataGridView call CellFormatting only once

我正在从返回的数据库创建动态 DataGridView table。我需要根据值将一些单元格更改为红色。我为 CellFormatting 事件分配了一个函数,但每次用户单击任何 cell/row(这会减慢表单速度)时都会调用该函数。

我想只在加载时执行函数。

我尝试通过循环 table 来设置样式,但背景颜色没有改变。我只在使用 CellFormatting 事件时才让它工作。

我的代码:

this.dgv.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.Dgv_CellFormatting);

并在函数中更改颜色

    private void Dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.Value != null)
        {
            if (e.ColumnIndex == 0)
            {
                if ((int)e.Value >= 5)
                {
                    e.CellStyle.BackColor = Color.Red;
                }
            }
        }

    }

使用 GridView_RowDataBound 事件。

if (e.Row.RowType == DataControlRowType.DataRow)
{
  //condition 
    If(e.Row.cells[3].Text.ToString() == "value2")
    {
    e.Row.BackColor = Drawing.Color.Red // 
    }
}

您可以将代码放入 "DataBindingComplete"。

例子

private void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dgv.Rows[0].Cells[0].Style.BackColor = Color.Red;
}