DataGridView.CellPainting 事件

定义

需要绘制单元格时发生。

C#
public event System.Windows.Forms.DataGridViewCellPaintingEventHandler CellPainting;

事件类型

DataGridViewCellPaintingEventHandler

示例

下面的代码示例演示如何使用此事件自定义特定列中所有单元格的外观。

此代码是有关如何:自定义 Windows 窗体 DataGridView 控件中单元格外观的更大示例的一部分。

C#
private void dataGridView1_CellPainting(object sender,
System.Windows.Forms.DataGridViewCellPaintingEventArgs e)
{
    if (this.dataGridView1.Columns["ContactName"].Index ==
        e.ColumnIndex && e.RowIndex >= 0)
    {
        Rectangle newRect = new Rectangle(e.CellBounds.X + 1,
            e.CellBounds.Y + 1, e.CellBounds.Width - 4,
            e.CellBounds.Height - 4);

        using (
            Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
            backColorBrush = new SolidBrush(e.CellStyle.BackColor))
        {
            using (Pen gridLinePen = new Pen(gridBrush))
            {
                // Erase the cell.
                e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                // Draw the grid lines (only the right and bottom lines;
                // DataGridView takes care of the others).
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                    e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                    e.CellBounds.Bottom - 1);
                e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                    e.CellBounds.Top, e.CellBounds.Right - 1,
                    e.CellBounds.Bottom);

                // Draw the inset highlight box.
                e.Graphics.DrawRectangle(Pens.Blue, newRect);

                // Draw the text content of the cell, ignoring alignment.
                if (e.Value != null)
                {
                    e.Graphics.DrawString((String)e.Value, e.CellStyle.Font,
                        Brushes.Crimson, e.CellBounds.X + 2,
                        e.CellBounds.Y + 2, StringFormat.GenericDefault);
                }
                e.Handled = true;
            }
        }
    }
}

注解

可以处理此事件以自定义控件中单元格的外观。 可以自己绘制整个单元格,或绘制单元格的特定部分,并使用 DataGridViewCellPaintingEventArgs.PaintBackgroundDataGridViewCellPaintingEventArgs.PaintContent 方法绘制其他部分。 还可以使用 VisualStyleRenderer 类使用当前主题绘制标准控件。 有关详细信息,请参阅 使用视觉样式呈现控件。 如果使用 Visual Studio 2005,则还可以访问可与控件一起使用DataGridView的大型标准映像库。

处理此事件时,应通过事件处理程序的参数访问单元格,而不是直接访问单元格。

有关如何处理事件的详细信息,请参阅 处理和引发事件

适用于

产品 版本
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
Windows Desktop 3.0, 3.1, 5, 6, 7

另请参阅