C# 动态更改datagridview单元格颜色
我有一个用数据填充的dataGridView对象。我想点击一个按钮,让它改变单元格背景的颜色。这就是我现在拥有的C# 动态更改datagridview单元格颜色,c#,dynamic,datagridview,cell,backcolor,C#,Dynamic,Datagridview,Cell,Backcolor,我有一个用数据填充的dataGridView对象。我想点击一个按钮,让它改变单元格背景的颜色。这就是我现在拥有的 foreach(DataGridViewRow row in dataGridView1.Rows) { foreach(DataGridViewColumn col in dataGridView1.Columns) { //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn
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++;
}
}
int count=0;
foreach(ItemDg.Rows中的DataGridViewRow行)
{
int qtyEntered=Convert.ToInt16(row.Cells[1].Value);
如果(qtyEntered实现您自己的DataGridViewTextBoxCell扩展,并像这样覆盖绘制方法:
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()});
请考虑使用DataBindingComplete事件更新样式。下一个代码将更改单元格的样式:
private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
}
如果希望网格中的每个单元格具有相同的背景色,可以执行以下操作:
dataGridView1.DefaultCellStyle.BackColor = Color.Green;
@t4thilina,很高兴它起到了作用。干杯:)如果您在表单的构造函数中尝试此操作,它将不起作用。不过,它在OnLoad覆盖中对我有效。我必须在之后调用dataGridView1.Refresh()
。这让我现在开始搜索…哈哈,我之前为“警告”和“确定”选择了最好的颜色,我也为“警告”选择了Color.oranged
,但Color.SpringGreen
为“确定”。你也可以通过this.YourColumn.CellTemplate
或this.dataGridView.Columns[“YourName”].CellTemplate