At runtime, I am adding a DataGridView to a windows form. The final column is a DataGridViewImageColumn:
Dim InfoIconColumn As New DataGridViewImageColumn
MyDataGridView.Columns.Insert(MyDataGridView.Columns.Count, InfoIconColumn)
Adding the following code will get my Information Icon (bitmap) to display in each of the column cells but NOT the column header:
Dim InfoIcon As New Bitmap("C:\MyPath\InfoIcon.bmp")
InfoIconColumn.Image = InfoIcon
Also, it is worth noting that the image displays 'perfectly' in the cells i.e. it is sized correctly to fit the cell.
However, I cannot find a way to add the same image to the column header cell. After some googling I used the following code which placed the image in the header cell but left me with two problems:
- The image did not 'auto-size' to the column headercell in the same way it did when added to the column cells. The image was slightly larger and blurred.
- By using the _CellPainting event slowed down performance i.e. when hovering over the DataGridView to highlight the selected row the highlighting lagged behind where my mouse was placed.
Here is the code:
Private Sub MyDataGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles MyDataGridView.CellPainting
Dim InfoIcon As Image = Image.FromFile("C:\MyPath\InfoIcon.bmp")
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
End Sub
Does anybody know of a way to solve my problem and get a nicely sized, sharp image into a DataGridViewImageColumn headercell at runtime?