Jon P
Jon P

Reputation: 821

DataGridViewRow.DefaultCellStyle Formatting

I have this code attached on RowValidating event of a DataGridView:

private void dgvSrc_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
    DataGridView dgv = sender as DataGridView;

    if (dgv.Rows[e.RowIndex].Cells["fullPath"].Value.ToString().Equals("none"))
        dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
    else
        dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
}

This works but not automatically, you need to focus or click first then select another row to see if its ForeColor is changed as red. I tried using Update and Refresh that does not automatically format the specific row. How can I fix this?

Upvotes: 0

Views: 789

Answers (3)

matzone
matzone

Reputation: 5719

You may do it in your dgv RowPrePaint event ..

Private void dgvSrc_RowPrePaint(object sender, DataGridViewCellCancelEventArgs e)
{
DataGridView dgv = sender as DataGridView;

if (dgv.Rows[e.RowIndex].Cells["fullPath"].Value.ToString().Equals("none"))
    dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
else
    dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
}

Upvotes: 0

V4Vendetta
V4Vendetta

Reputation: 38200

Use the CellFormatting event of the DataGridView

dgv.CellFormatting += dgv_CellFormatting

Handle it like

void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if(dgv.Rows[e.RowIndex].Cells["fullPath"].Value.ToString().Equals("none"))
      dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Red;
    else
      dgv.Rows[e.RowIndex].DefaultCellStyle.ForeColor = Color.Black;
}

Upvotes: 1

Nikita B
Nikita B

Reputation: 3333

You are subscribing to the wrong event. I think, you need this one: CellValueChanged

Upvotes: 0

Related Questions