Mike
Mike

Reputation: 1312

DataGridView call CellFormatting only once

I'm creating a dynamic DataGridView from a returned DB table. I need to change some cells to Red based on the value. I assigned a function to the CellFormatting event, but the function get called every time the user clicks on any cell/row (which slows down the form).

I would like to execute the function only on load.

I tried to set the style by looping the table, but the back color didn't change. I got it to work only when using the CellFormatting event.

the code I have:

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

and in the function I change the color

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

    }

Upvotes: 0

Views: 3021

Answers (2)

Angus Chung
Angus Chung

Reputation: 1587

You can put your code in "DataBindingComplete".

Example

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

Upvotes: 2

fuzzybear
fuzzybear

Reputation: 2405

Using GridView_RowDataBound event .

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

Upvotes: 0

Related Questions