如何:在 Windows 窗体 DataGridView 控件的单元格中显示图像

图片或图形是可在数据行中显示的值之一。 这些图形通常采用员工照片或公司徽标的形式。

DataGridView 控件中显示数据时,插入图片非常简单。 控件 DataGridView 能够本地处理 Image 类支持的所有图像格式,以及某些数据库使用的 OLE 图片格式。

DataGridView 控件的数据源如果有一列图像,DataGridView 控件将自动显示这些图像。

下面的代码示例演示如何从嵌入的资源中提取图标,并将其转换为位图,以便在图像列的每个单元格中显示。 有关将文本单元格值替换为相应图像的另一个示例,请参阅 How to: Customize Data Formatting in the Windows Forms DataGridView Control.

示例:

private void createGraphicsColumn()
{
    Icon treeIcon = new Icon(this.GetType(), "tree.ico");
    DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();
    iconColumn.Image = treeIcon.ToBitmap();
    iconColumn.Name = "Tree";
    iconColumn.HeaderText = "Nice tree";
    dataGridView1.Columns.Insert(2, iconColumn);
}
Public Sub CreateGraphicsColumn()

    Dim treeIcon As New Icon(Me.GetType(), "tree.ico")
    Dim iconColumn As New DataGridViewImageColumn()

    With iconColumn
        .Image = treeIcon.ToBitmap()
        .Name = "Tree"
        .HeaderText = "Nice tree"
    End With

    dataGridView1.Columns.Insert(2, iconColumn)

End Sub

编译代码

此示例需要:

另请参阅