Question

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?

Pas de solution correcte

Autres conseils

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

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

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top