0

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?

Jon P
  • 826
  • 1
  • 7
  • 20

3 Answers3

1

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;
}
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82
  • Found this useful but looping through all the rows after loading the data then using the conditions above seems faster on loading. Thanks anyway – Jon P Jun 11 '13 at 06:53
  • 1
    @nathan742 "Thank you anyway" As the question was asked, @ V4Vendetta probably give you the best answer. (I was starting to write the same, he beat me from a few seconds). "Looping through all the rows after loading the data" is a possible solution but it supposes that values the Grid is readonly. In your question you wrote "This works but not automatically,". I don't understand your comment "Man". – Chris Jun 11 '13 at 20:48
  • 1
    @Chris i guess what he means by automatically is it sets it only once when the loop is run and not at al times when the value might change – V4Vendetta Jun 12 '13 at 05:28
  • Yep, @V4Vendetta is right. That's what I did and what I meant. – Jon P Jun 13 '13 at 02:53
0

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

Nikita B
  • 3,303
  • 1
  • 23
  • 41
0

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;
}
matzone
  • 5,703
  • 3
  • 17
  • 20