Add Image on DatagridView Cell Header

Windows Forms DataGridView control does not have any property by which we can add an Image on the DataGrid View Header.

But we can add Image on DataGridView programetically and for this purpose we can use CellPainting event of DataGridView control.

Let's say, you have an image that you would like to draw on a DataGridView header.

First of all, we need to create an Image object from the image file. The following code creates an Image object from a GIF file. The FromFile static method of Image class creates an Image object from a file.

Note: In this code, you will replace C:\AddEmoticons04247.gif with with the full path and file name of your image file.

Dim InfoIcon As Image = Image.FromFile("C:\AddEmoticons04247.gif")

After that, we simply need to draw the image using Graphics.DrawImage metho on the CellPainting event handler. Go to your DataGridView control events and double click on CellPainting method in Properties Window and write th following code.


If e.RowIndex = -1 AndAlso e.ColumnIndex = MyDataGridView.Columns.Count - 1 Then

                e.Paint(e.CellBounds, DataGridViewPaintParts.All And Not DataGridViewPaintParts.ContentForeground)

                e.Graphics.DrawImage(InfoIcon, e.CellBounds)

                e.Handled = True

            End If


Now if you run the application, you will see image appears on the header of the DataGridView control.


ImageOnGridHeader.JPG 


Similar Articles