在 DataGridView 中的列之前为行着色

Coloring rows before columns in DataGridView

我正在创建一个程序,它使用 DataGridView 来编辑 SQL 数据库中的记录。我的项目经理要求根据行在一段时间 window 内是否已插入、更新或标记为删除,将行标记为绿色、黄色或红色。他还希望使用该列对 DataGridView 颜色的浅灰色进行排序。为了处理这个问题,我在表单中创建了以下事件处理程序:

    private void OnRowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
    {
        //get the row
        DataRow row = ((DataRowView)this.dataGridView.Rows[e.RowIndex].DataBoundItem).Row;

        //color the row
        try
        {
            //REDACTED
            //gets booleans used below
            //REDACTED

            if (softDeleted)
                this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 213, 91, 95);    //red
            else if (inserted)
                this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 83, 223, 146);   //green
            else if (updated)
                this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.FromArgb(255, 234, 218, 106);  //yellow
            else
                this.dataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Empty;
        }
        //on failure, abort coloring
        catch(Exception ex)
        {
            MessageBox.Show("Unable to get data required for coloring - " + ex.Message + ".\n Coloring disabled.");
            Logging.logException(ex);
            this.dataGridView.RowPrePaint -= OnRowPrePaint;
        }
    }
    private void OnSorted(object sender, EventArgs e)
    {
        //remove color from previous sort column and add to new
        if (this.mLastSortColumnIndex != -1)
        {
            this.dataGridView.Columns[this.mLastSortColumnIndex].DefaultCellStyle.BackColor = Color.Empty;
        }
        this.mLastSortColumnIndex = this.dataGridView.SortedColumn.Index;
        this.dataGridView.SortedColumn.DefaultCellStyle.BackColor = Color.LightGray;
    }

效果很好,我很满意!或者是,直到我的项目经理坚持排序颜色(列颜色)覆盖行颜色。我的尝试都失败了 - 有什么办法可以彻底解决这个问题吗?

下图 - 左侧为当前,右侧为所需。

向 CellPainting 事件添加处理程序

void OnGridCellPainting(object sender, System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == mLastSortColumnIndex)
        e.CellStyle.BackColor = Color.LightGray;
}

此方法在 RowPrePaint 之后为排序列中的单元格设置 LightGray 颜色