在运行时更改数据网格视图行颜色

本文关键字:网格 视图 颜色 数据网 数据 运行时 | 更新日期: 2023-09-27 18:37:25

我正在为我正在开发的控件继承 DataGridView 控件。我的目标是使每一行的颜色表示可以在运行时更改的对象状态。我的对象实现了可观察设计模式。因此,我决定开发自己的 DataGridViewRow 类,实现观察者模式并让我的行观察对象。在本课程中,我有此方法:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[state];
    DefaultCellStyle.ForeColor = m_ETForeColors[state];
}

我暂时无法观察我的对象,因此,为了测试颜色变化,我在 SelectionChanged 事件上的选定行上调用我的 UpdateColors 方法。

现在是它不起作用的时刻!我以前选择的行保持蓝色(就像选择它们时一样),当我滚动时,单元格文本是分层的。我尝试调用DataGridView.Refresh(),但这也不起作用。

我必须添加我的 datagridview 未绑定到数据源:我不知道我在运行时之前有多少列,所以我手动输入它。

谁能说我做错了什么?

====

====== 更新 ==========

这有效:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;
    DefaultCellStyle.ForeColor = System.Drawing.Color.Black;
}

但这不起作用:

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[nEtattech];
    DefaultCellStyle.ForeColor = m_ETForeColors[nEtattech];
}

跟:

    System.Drawing.Color[] m_ETBackColors = new System.Drawing.Color[] { };
    System.Drawing.Color[] m_ETForeColors = new System.Drawing.Color[] { };

没有数组溢出:它们是构造函数参数。

在运行时更改数据网格视图行颜色

好的,发现了错误。我使用的颜色是这样创建的:

System.Drawing.Color.FromArgb(value)

不好的是,值是一个整数,表示 alpha 设置为 0 的颜色。
感谢这篇文章:MSDN社交帖子,我了解到单元格样式不支持ARGB颜色,除非alpha设置为255(它们仅支持RGB颜色)。

所以我结束了使用它,它有效,但肯定有一种更优雅的方法:

System.Drawing.Color.FromArgb(255, System.Drawing.Color.FromArgb(value));

使用CellFormatting事件来执行此操作:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if (this.dataGridView1.Rows[e.RowIndex].Cells["SomeStuff"].Value.ToString()=="YourCondition")
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
  else
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
}