winform 修改DataGdataridViewButton 颜色

该文介绍如何修改DataGridView中的列背景色,通过设置FlatStyle属性和DefaultCellStyle.BackColor,可以改变整列颜色。对于单个单元格,同样设置FlatStyle和Style.BackColor。此外,可以通过CellFormatting事件有条件地改变单元格颜色,实现动态效果。
摘要由CSDN通过智能技术生成

更改整个列的背景颜色

作为一个选项,您可以设置to 的FlatStyle属性并将其设置为您想要的颜色:DataGdataridViewButtonColumnFlatStyle.BackColor

var C1 = new DataGridViewButtonColumn() { Name = “C1” };
C1.FlatStyle = FlatStyle.Flat;
C1.DefaultCellStyle.BackColor = Color.Red;
更改单个单元格的背景颜色

如果要为不同的单元格设置不同的颜色,将FlatStyle列或单元格设置为后,将不同的单元格设置为不同的颜色Flat就足够了Style.BackColor:

var cell = ((DataGridViewButtonCell)dataGridView1.Rows[1].Cells[0]);
cell.FlatStyle = FlatStyle.Flat;
dataGridView1.Rows[1].Cells[0].Style.BackColor = Color.Green;
如果要有条件地更改单元格的背景颜色,可以在CellFormatting基于单元格值的事件中进行。

笔记

如果您更喜欢标准外观而Button不是平面样式,您可以处理CellPaint事件:

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
if (e.ColumnIndex == 0) // Also you can check for specific row by e.RowIndex
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All
& ~( DataGridViewPaintParts.ContentForeground));
var r = e.CellBounds;
r.Inflate(-4, -4);
e.Graphics.FillRectangle(Brushes.Red, r);
e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);
e.Handled = true;
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值