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