改变DataGridView中的DataGridViewButtonCell单元格的背景色.

尝试了下面的代码,但无法改变单元格的背景色.

DataGridViewRow row = new DataGridViewRow();
DataGridViewButtonCell dg_btn_cell = new DataGridViewButtonCell();
dg_btn_cell.Value = "Component" + i;
dg_btn_cell.Style.BackColor = Color.Red;
dg_btn_cell.Style.ForeColor = Color.Black;
dg_btn_cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
row.Cells.Add(dg_btn_cell);

网上查了下资料,这里整理下,主要有3种方式,其中第三种方式比较理想.

方式1,绘制按钮,背景色改变了,但是按钮效果没有了.

来自链接https://bbs.csdn.net/topics/390579809

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        e.Handled = true;
        using (SolidBrush brush = new SolidBrush(Color.Red))
        {
            e.Graphics.FillRectangle(brush, e.CellBounds);
        }
        ControlPaint.DrawBorder(e.Graphics, e.CellBounds, Color.Yellow, ButtonBorderStyle.Outset);
    }
}

其他两种方式来自链接https://bbs.csdn.net/topics/390583120c# - Change Color of Button in DataGridView Cell - Stack Overflow

方式2,在Program.cs中屏蔽该段代码

//Application.EnableVisualStyles();

下面的代码执行后,单元格中button的背景色确实改变了,但是界面上的其他控件显示效果会受到影响,如System.Windows.Forms.Button将显示为经典的windows(我的系统为win10)按钮效果.

dg_btn_cell.Style.BackColor = Color.Red;

方式3 ,设置DataGridViewButtonCell的FlatStyle属性,Popup或者Flat.

DataGridViewRow row = new DataGridViewRow();
DataGridViewButtonCell dg_btn_cell = new DataGridViewButtonCell();
dg_btn_cell.Value = "Component" + i;
dg_btn_cell.FlatStyle = FlatStyle.Flat;//FlatStyle.Popup;
dg_btn_cell.Style.BackColor = Color.Red;
dg_btn_cell.Style.ForeColor = Color.Black;
dg_btn_cell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
row.Cells.Add(dg_btn_cell);

其他实现:c# - Change Color of Button in DataGridView Cell - Stack Overflow中提到可以通过编写DataGridViewButtonCell的派生类,然后在派生类中重载paint方法中调用ButtonRenderer的DrawButton方法来定制DataGridViewButtonCell的外观效果.

ButtonRenderer链接 ButtonRenderer 类 (System.Windows.Forms) | Microsoft Learn

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值