Handle Custom painting in DataGridView

Thursday, February 12, 2009

How to Handle Custom painting in DataGridView?


The DataGridView control provides several properties that you can use to adjust the appearance and basic behavior (look and feel) of its cells, rows, and columns. If you have requirements that go beyond the capabilities of the DataGridViewCellStyle class, you can perform custom drawing of the cell or row content. To paint cells and rows yourself, you can handle various DataGridView painting events such as RowPrePaint, CellPainting and RowPostPaint.

Paint Parts

One important part of custom painting is the concept of paint parts. The DataGridViewPainParts enumeration is used to specify what parts a cell paints. Enum values can be combined together to have a cell paint or not paint specific parts. Here are the different parts:

PaintPart: Example ForeColor value for retrieved object All :All parts are

paintedBackground: The background of the cell is painted using the cell’s background color

Border :The borders are paintedContentBackground: The background part of the cell’s content is painted.

ContentForeground: The foreground part of the cell’s content is painted

ErrorIcon: The error icon is paintedFocus: The focus rectangle for the cell is painted

Focus :The focus rectangle for the cell is painted

SelectionBackground: The background is painted selected if the cell is selected.

Row Pre Paint and Post Paint

You can control the appearance of DataGridView rows by handling one or both of the DataGridView.RowPrePaint and DataGridView.RowPostPaint events. These events are designed so that you can paint only what you want to while letting the DataGridView control paint the rest. For example, if you want to paint a custom background, you can handle the DataGridView.RowPrePaint event and let the individual cells paint their own foreground content. In the RowPrePaint event you can set the PaintParts event args property to easily customize how the cells paint. For example, if you want to keep cells from painting any selection or focus, your RowPrePaint event would set the PaintParts property like so:

e.PaintParts = DataGridViewPaintParts.All & ~(DataGridViewPaintParts.Focus DataGridViewPaintParts.SelectionBackground);

Which could also be written as:

e.PaintParts = (DataGridViewPaintParts.Background DataGridViewPaintParts.Border DataGridViewPaintParts.ContentBackground DataGridViewPaintParts.ContentForeground DataGridViewPaintParts.ErrorIcon);

Alternately, you can let the cells paint themselves and add custom foreground content in a handler for the DataGridView.RowPostPaint event. You can also disable cell painting and paint everything yourself in a DataGridView.RowPrePaint event handler

we will see more on datagridview in our next posts.

0 comments:

Back to TOP