DataGridViewCellPaintingEventHandler Delegate
Collapse the table of content
Expand the table of content

DataGridViewCellPaintingEventHandler Delegate


Represents the method that will handle the CellPainting event of a DataGridView.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (in System.Windows.Forms.dll)

public delegate void DataGridViewCellPaintingEventHandler(
	object sender,
	DataGridViewCellPaintingEventArgs e


Type: System.Object

The source of the event.

Type: System.Windows.Forms.DataGridViewCellPaintingEventArgs

A DataGridViewCellPaintingEventArgs that contains the event data.

When you create a DataGridViewCellPaintingEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called whenever the event occurs, unless you remove the delegate. For more information about event-handler delegates, see NIB: Events and Delegates.

Legacy Code Example

The following example illustrates the use of this event to customize the appearance of all cells in a particular column.

This code is part of a larger example available in How to: Customize the Appearance of Cells in the Windows Forms DataGridView Control.

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,

                // 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;

.NET Framework
Available since 2.0
Return to top
© 2015 Microsoft