如何显示一个DataGridView列标题的图像? [英] How to display an image in a datagridview column header?

查看:567
本文介绍了如何显示一个DataGridView列标题的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在运行时,我加入一个DataGridView到Windows窗体。最后一列是一个DataGridViewImageColumn:

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)

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

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.

不过,我不能找到一种方法相同​​的图像添加到列标题单元格。一些谷歌搜索后,我用下面的code里面放置图像中的标题单元格,但给我留下了两个问题:

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. 图像没有'自动调整大小到时添加到列单元格就做过同样的方式在列headercell。图像略大和模糊。

  2. 悬停在DataGridView时突出显示的选定行高亮落后的地方我的鼠标放在后面
  3. 将使用_CellPainting活动放缓的表现,即。

下面是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

有谁知道的方式来解决我的问题,并在运行时得到一个很好的大小,锐利的影像变成DataGridViewImageColumn headercell?

Does anybody know of a way to solve my problem and get a nicely sized, sharp image into a DataGridViewImageColumn headercell at runtime?

推荐答案

你可以做到这一点的方法之一是使用CellsPainting事件绘制
位图特定的标题单元格。这里是code,这是否
假设位图是在图像列表。

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;
    }
}

这篇关于如何显示一个DataGridView列标题的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆