C# DataGridView BackColor 未被覆盖

C# DataGridView BackColor Not Overwritten

我的申请表上有 DataGridView。从数据库中的 table 检索数据并将它们显示在 DataGridView 中后,我将 green 颜色应用于某些单元格的 BackColor 如果满足特定条件,则行。 在这些单元格被着色 green 之后,程序使它们经历另一个条件,该条件为整行的 BackColor red 如果他们不满足条件。

但是,预着色的单元格似乎无法用新颜色覆盖。 即使我应用以下代码为整行着色 red,它也只适用于未预先着色的单元格。

for(int i=0; i<myDataGridview.Rows.Count; i++){  
    if(/*a certain condition FAILS*/){
        myDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.Red;
    }
}

现在,我正在为那些预先着色的单元格 红色 一个一个着色,但这需要很多时间和代码,例如:

for(int i=0; i<myDataGridview.Rows.Count; i++){  
    if(/*a certain condition FAILS*/){
        //Trying to color the whole row RED, but not working
        myDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.Red;
        //Manually color the cells, which are pre-colored to green, RED
        myDataGridView.Rows[i].Cells[6].Style.BackColor = Color.Red;
        myDataGridView.Rows[i].Cells[7].Style.BackColor = Color.Red;
        ....
        myDataGridView.Rows[i].Cells[13].Style.BackColor = Color.Red;
        myDataGridView.Rows[i].Cells[16].Style.BackColor = Color.Red;
    }
}

我想知道是否有更好的方法来覆盖背景颜色。有人可以帮忙吗?

下面是一个例子(仿)DataGridView。

第一个条件失败的人会自动将整行变成红色,这很有效。但是,如果他们通过了第一个条件并使 "Passed1" 单元格变为绿色,然后第二个条件未通过,如您所见,这些单元格将保持绿色。我想将整行着色为红色,甚至将预着色为绿色的单元格覆盖为红色。

datagridview 控件存在问题,在使用 DefaultCellStyle 属性 显示表单之前,您无法更改任何单元格的颜色。因此 运行 的方法或调用 Shown() 之前触发的事件不会改变颜色。这就是问题 probably.May 你必须创建一个绘画方法并在 Shown() 之前调用它。

绘制单元格时,单元格背景颜色具有优先顺序。从顶部开始,它将向下层叠列表直到设置颜色*:

  1. Cell.Style.BackColor
  2. Row.DefaultCellStyle.BackColor
  3. DataGridView.AlternatingRowsDefaultCellStyle.BackColor
  4. DataGridView.RowsDefaultCellStyle.BackColor
  5. Column.DefaultCellStyle.BackColor
  6. DataGridView.DefaultCellStyle.BackColor

* 此列表并不广泛,可能不包括所有可能的可访问背景颜色 属性.


您可能正在做类似于为 Passed1 列中的单元格设置 Cell.Style.BackColor 的操作,然后是您发布的代码逻辑。这会给出您所看到的结果,因为 Green 的优先级高于 Red 设置的位置:

假设您的两个 Passed 列的条件是二进制的(YesNo),您可以通过 "lowering" [=19= 的优先级来解决这个问题] 背景通过设置 Column.DefaultCellStyle.BackColor:

private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    this.dataGridView1.Columns["Passed1"].DefaultCellStyle.BackColor = Color.Green;
    this.dataGridView1.Columns["Passed2"].DefaultCellStyle.BackColor = Color.Green;

    foreach (DataGridViewRow row in this.dataGridView1.Rows)
    {
        if (row.Cells["Passed1"].Value.ToString() == "No" || row.Cells["Passed2"].Value.ToString() == "No")
        {
            row.DefaultCellStyle.BackColor = Color.Red;
        }
    }
}

这导致: