动态更改datagridview单元格颜色
问题描述:
我有一个数据填充的dataGridView对象。我想单击一个按钮并使其更改单元格背景的颜色。这是我目前有动态更改datagridview单元格颜色
foreach(DataGridViewRow row in dataGridView1.Rows)
{
foreach(DataGridViewColumn col in dataGridView1.Columns)
{
//row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
//col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
}
}
这三个原因,重复地重新绘制了自身的表,并试图重新大小的表变得一团糟。单击单元格时,该值将保持高亮显示,并且背景颜色不会更改。
问:如何在表格存在后更改单个单元格的背景颜色?
答
这对我的作品
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
答
由于它的工作
我在这里用这个工作由数量字段是零意味着它表明,细胞是红色
int count = 0;
foreach (DataGridViewRow row in ItemDg.Rows)
{
int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
if (qtyEntered <= 0)
{
ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
ItemDg[1, count].Style.BackColor = Color.Red;
ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory
}
ItemDg[0, count].Value = "0";//assign a default value to quantity enter
count++;
}
}
答
实施您自己的DataGridViewTextBoxCell的扩展并重写像这样的Paint方法:
class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
if (value != null)
{
if ((bool) value)
{
cellStyle.BackColor = Color.LightGreen;
}
else
{
cellStyle.BackColor = Color.OrangeRed;
}
}
base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
}
然后在你列的CellTemplate属性设置为你的类
columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
+0
大声笑,我之前选择了'警告'和'好'的最佳颜色,而且我最终选择了'Color.OrangeRed'作为'警告',但'Color.SpringGreen'选择了'OK'。 – n00dles
添加的实例的代码;在最后 – szakwani
亲爱的Ehsan,谢谢你的提示,它适用于我。 – t4thilina
@ t4thilina,很高兴帮助。欢呼声:) – Ehsan