views:

1748

answers:

1

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:

  1. 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.
  2. 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?

+1  A: 

One way you can do this is to use the CellsPainting event to draw the bitmap for a particular header cell. Here is code that does this assuming the bitmap is in an imagelist.

//this.images is an ImageList with your bitmaps
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == 1 && e.RowIndex == -1)
    {
        e.PaintBackground(e.ClipBounds, false);

        Point pt = e.CellBounds.Location;  // where you want the bitmap in the cell

        int offset = (e.CellBounds.Width - this.images.ImageSize.Width) / 2;
        pt.X += offset;
        pt.Y += 1;
        this.images.Draw(e.Graphics, pt, 0);
        e.Handled = true;
    }
}
Lucas McCoy
@Lucas - Thanks for the advice. I will give this try and report back...