【发布时间】:2018-03-02 23:24:33
【问题描述】:
我的表单申请中有DataGridView。从数据库中的表中检索数据并在DataGridView 中显示它们后,如果满足特定条件,我将green 颜色应用于某些单元格的行的
但是,似乎预着色的单元格不能用新颜色覆盖。 即使我应用以下代码为整行着色红色,它也仅适用于未预先着色的单元格。
for(int i=0; i<myDataGridview.Rows.Count; i++){
if(/*a certain condition FAILS*/){
myDataGridView.Rows[i].DefaultCellStyle.BackColor = Color.Red;
}
}
现在,我正在将那些预先着色的单元格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”单元格变为绿色,然后不符合第二个条件,如您所见,这些单元格将保持绿色。我想将整行着色为红色,甚至将预着色为绿色的单元格覆盖为红色。
【问题讨论】:
-
a) 解释“预着色”! b) 请参阅 here 以获取在
CellPainting事件中为单元格着色的示例。如果您为全套条件编写代码就足够了。 -
如果一个新的 BackColor 已应用到一个单元格(即预着色),则该单元格的 BackColor 不能更改为另一种颜色,即使我尝试使用 myDataGridView 为包括该单元格在内的整行着色。行[i].DefaultCellStyle.BackColor
-
这将是默认值和覆盖值之间的区别。使用 cell.BackColor 覆盖默认值或先前的更改!另外:尝试将所有颜色等集中在 CellPainting 中。
-
在我贴在帖子中的图片中,ID:2、4 和 5 的行不能完全着色为红色,它们的“Passed1”单元格保持绿色。
-
好吧,如果您只是将单元格颜色更改为绿色,则只是更改了该单元格,而不是整行。请阅读How to Ask 并采取tour
标签: c# datagridview backcolor