DataGridView:DataGridViewComboBoxColumn列,点击更改Button颜色

本文介绍了在DataGridView表格的按钮列中,通过两种方式实现点击按钮后弹出色彩选择器并更新按钮背景色:方式一是设置列样式配合CellClick事件,方式二是利用CellPainting事件进行自定义绘制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题简述:

有一个DataGridView表格,第二列样式为按钮样式DataGridViewButtonColumn,要求用户在点击按钮时,弹出颜色控件,然后将选择的颜色置为ButtonCell的背景色。

有两种实现方式:

方式一:

设置列样式,代码如下:

//设置表格按钮样式
DataGridViewButtonColumn buttonColumn = gridView.Columns[1] as DataGridViewButtonColumn;
buttonColumn.FlatStyle = FlatStyle.Popup;  //设置按钮样式


/// <summary>
/// 点击表格按钮,弹出颜色控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GridViewColor_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == 1)
    {
        ColorDialog myColorDlg = new ColorDialog();
        if (myColorDlg.ShowDialog() == DialogResult.OK)
        {
             DataGridViewButtonCell buttonCell = this.GridViewColor.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewButtonCell;
             buttonCell.Style.BackColor = myColorDlg.Color;
        }
    }
}

样式如下:

方式二:

使用CellPainting()事件,代码如下:

private void GridViewColor_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
     if (e.RowIndex >= 0 && e.ColumnIndex == 1)
     {
          DataGridViewButtonCell buttonCell = this.GridViewColor.Rows[e.RowIndex].Cells[1] as DataGridViewButtonCell;
          using (SolidBrush brush = new SolidBrush(buttonCell.Style.BackColor))
          {
               e.Graphics.FillRectangle(brush, e.CellBounds);
          }
          ControlPaint.DrawBorder(e.Graphics, e.CellBounds, this.GridViewColor.GridColor, ButtonBorderStyle.Outset); 
          e.Handled = true;   //这句代码一定要加,不然不会重新绘制表格
      }
}

/// <summary>
/// 点击表格按钮,弹出颜色控件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void GridViewColor_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex == 1)
    {
        ColorDialog myColorDlg = new ColorDialog();
        if (myColorDlg.ShowDialog() == DialogResult.OK)
        {
             DataGridViewButtonCell buttonCell = this.GridViewColor.Rows[e.RowIndex].Cells[e.ColumnIndex] as DataGridViewButtonCell;
             buttonCell.Style.BackColor = myColorDlg.Color;
        }
    }
}

样式如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值