【发布时间】: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