改变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/390583120https://stackoverflow.com/questions/586829/change-color-of-button-in-datagridview-cell

方式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);

其他实现:https://stackoverflow.com/questions/586829/change-color-of-button-in-datagridview-cell中提到可以通过编写DataGridViewButtonCell的派生类,然后在派生类中重载paint方法中调用ButtonRenderer的DrawButton方法来定制DataGridViewButtonCell的外观效果.

ButtonRenderer链接 https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.forms.buttonrenderer?redirectedfrom=MSDN&view=netframework-4.7.2

猜你喜欢

转载自blog.csdn.net/dd_zhouqian/article/details/89377962
今日推荐