问题简述:
有一个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;
}
}
}
样式如下:

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

被折叠的 条评论
为什么被折叠?



