繁体   English   中英

为DataGridView中的列之前的行着色

[英]Coloring rows before columns in DataGridView

我正在创建一个程序,该程序使用DataGridView编辑SQL数据库中的记录。 我的项目经理要求将行着色为绿色,黄色或红色,具体取决于是否已在时间窗口内将其插入,更新或标记为删除。 他还希望拥有用于对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颜色

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM