如何在 datagridview 列标题中显示图像? [英] How to display an image in a datagridview column header?
问题描述
在运行时,我将一个 DataGridView
添加到 Windows 窗体中.最后一列是 DataGridViewImageColumn
:
At run-time, 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:MyPathInfoIcon.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:
- 图像没有像添加到列单元格时那样自动调整"到列标题单元格.图像稍大且模糊.
- 使用
_CellPainting
事件会降低性能,即当鼠标悬停在DataGridView
上以突出显示所选行时,突出显示滞后于放置鼠标的位置.
- 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 theDataGridView
to highlight the selected row the highlighting lagged behind where my mouse was placed.
代码如下:
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:MyPathInfoIcon.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
标题单元格的方法吗?
Does anybody know of a way to solve my problem and get a nicely sized, sharp image into a DataGridViewImageColumn
headercell at run-time?
推荐答案
一种方法是使用 CellsPainting
事件来绘制特定标题单元格的位图.这是执行此操作的代码假设位图在 imagelist
中.
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屋!