【问题标题】:DataGridView call CellFormatting only onceDataGridView 只调用一次 CellFormatting
【发布时间】:2015-06-16 07:07:57
【问题描述】:

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

我想只在加载时执行该功能。

我尝试通过循环表格来设置样式,但背面颜色没有改变。我只有在使用 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;
                }
            }
        }

    }

【问题讨论】:

  • 请发布您目前拥有的任何代码。

标签: c# winforms datagridview background-color


【解决方案1】:

您可以将您的代码放在“DataBindingComplete”中。

示例

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

【讨论】:

    【解决方案2】:

    使用 GridView_RowDataBound 事件。

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

    【讨论】:

    • 这将在每个加载或数据绑定事件中运行一次。 DataControlRowType.Datarow 确保从循环中排除页眉/页脚
    • 我找不到 RowDataBound 事件。 this.dgv.* 没有这个事件。
    • Mike 对不起,我的错,我在想你可以使用 DataGrid.LoadingRow 的 winform 的 webforms,在 DataGridRow 被实例化之后发生,这样你就可以在使用它之前对其进行自定义。 msdn.microsoft.com/en-us/library/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-10
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2017-06-08
    • 2016-08-18
    • 2013-01-09
    相关资源
    最近更新 更多