DataGridViewRow.DefaultCellStyle Formatting

本文关键字:Formatting DefaultCellStyle DataGridViewRow | 更新日期: 2023-09-27 18:17:53

我将此代码附加在DataGridViewRowValidating事件上:

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

这是有效的,但不是自动的,你需要先聚焦或点击,然后选择另一行,看看它的ForeColor是否被改变为红色。我尝试使用UpdateRefresh,不自动格式化特定行。我该如何解决这个问题?

DataGridViewRow.DefaultCellStyle Formatting

使用DataGridViewCellFormatting事件

dgv.CellFormatting += dgv_CellFormatting

那样处理
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;
}

您订阅了错误的事件。我认为,你需要这个cellvaluechange

您可以在dgv RowPrePaint事件中这样做。

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