【问题标题】:Coloring rows before columns in DataGridView在 DataGridView 中的列之前为行着色
【发布时间】:2015-01-20 19:06:59
【问题描述】:

我正在创建一个程序,它使用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;
    }

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

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

【问题讨论】:

    标签: c# datagridview paint


    【解决方案1】:

    为 CellPainting 事件添加处理程序

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

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

    【讨论】:

    • 我不知道在搜索 API 以寻找可能的修复程序时我是如何错过该事件的......就像一个魅力;谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多