动态更改数据网格视图单元格颜色
本文关键字:视图 单元格 颜色 网格 数据网 数据 动态 | 更新日期: 2023-09-27 18:23:44
我有一个用数据填充的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
}
}
所有这三种情况都会导致表以重叠的方式重新绘制,并且试图重新调整表的大小会变得一团糟。单击单元格时,该值保持高亮显示,背景颜色不变。
Q: 表格存在后,如何更改单个单元格的背景颜色?
这适用于我的
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
实现您自己的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()});
感谢的工作
这里我完成了这个由数量字段是零意味着它表明细胞是红色
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++;
}
}
如果你想让网格中的每个单元格都有相同的背景色,你可以这样做:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
Considere使用DataBindingComplete事件更新样式。下一个代码更改单元格的样式:
private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
}