我正在创建一个程序,它使用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;
}
这非常有效,我对它很满意!或者是,直到我的项目经理坚持排序颜色(列着色)覆盖行着色。我的尝试都遇到了失败 - 有没有办法彻底解决这个问题?
下图 - 左侧电流,右侧电流。
答案 0 :(得分: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颜色