如何在datagridview列标题中显示图像?

7 c# vb.net datagridview winforms

在运行时,我正在添加DataGridView一个Windows窗体.最后一栏是DataGridViewImageColumn:

Dim InfoIconColumn As New DataGridViewImageColumn
MyDataGridView.Columns.Insert(MyDataGridView.Columns.Count, InfoIconColumn)
Run Code Online (Sandbox Code Playgroud)

添加以下代码将使我的信息图标(位图)显示在每个列单元格中,但不显示在列标题中:

Dim InfoIcon As New Bitmap("C:\MyPath\InfoIcon.bmp")
InfoIconColumn.Image = InfoIcon
Run Code Online (Sandbox Code Playgroud)

此外,值得注意的是,图像在细胞中"完美"显示,即它的大小正确以适合细胞.

但是,我找不到将相同图像添加到列标题单元格的方法.经过一些谷歌搜索我使用下面的代码将图像放在标题单元格中,但给我留下了两个问题:

  1. 图像没有像添加到列单元格时那样对列标题单元"自动调整大小".图像略大且模糊.
  2. 通过使用_CellPainting事件减慢性能,即当悬停在DataGridView突出显示所选行时突出显示滞后于放置鼠标的位置.

这是代码:

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
Run Code Online (Sandbox Code Playgroud)

有没有人知道解决我的问题的方法,并DataGridViewImageColumn在运行时获得一个大小,清晰的图像到标题单元?

Kre*_*dns 15

一种方法是使用CellsPainting事件来绘制特定标题单元格的位图.假设位图在一个中,这是执行此操作的代码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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您没有将Image存储在ImageList中,请将第二个LOC修改为; e.Graphics.DrawImage(image,pt); 也有效. (2认同)