C# - DataGridView - 同一行上的图像和文本

时间:2012-07-14 04:46:08

标签: c# .net winforms datagridview

我在DataGridView上寻找类似的东西:

Image  | Text | 
Text   | Text |
Image  | Text

基本上,我只想在同一行上放置图像单元格和文本单元格。 我能够使用不同的类型,例如:复选框,文本等... 但是我无法使用它来处理图像。

我收到此错误:Invalid Cast from 'System.String' to 'System.Drawing.Image'

有人知道解决方案或建议我应该怎么做? 感谢

3 个答案:

答案 0 :(得分:7)

在某些单元格中显示DataGridViewImageColumn类型的列是相对容易的。

您需要做的就是用DataGridViewTextBoxCell替换所需的单元格。

例如,如果我将以下图像列添加到我的网格中:

DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn .Name = "ImageColumn";
imageColumn .HeaderText = "An Image!";
Image i = Image.FromFile(@"C:\Pictures\TestPicture.jpg");
imageColumn.Image = i;
dataGridView1.Columns.Add(imageColumn);

您可以使用类似的文本替换给定的单元格(在按钮处理程序中,但您也可以在数据绑定完整处理程序中的某处执行此操作)。

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows[3].Cells["ImageColumn"] = new DataGridViewTextBoxCell();
    dataGridView1.Rows[3].Cells["ImageColumn"].Value = "Some text!";  
}

如果您需要不同的图像(需要绑定到图像类型的属性)并且需要不同的文本,此解决方案会为您留下一些工作。由于图像列的Value属性是Image类型,因此无法使用相同的绑定。

您可以创建自己的已覆盖图像列来处理此问题,但这可能会有点工作,可能不会为自己付出代价而只需设置直接需要文本的单元格的值。

答案 1 :(得分:1)

我发现我必须处理DataGridViewCellFormattingEventHandler并在DataGridViewCellFormattingEventHandler中分配图像(在退出时抛出异常)。

在我分配DataGridViewCellFormattingEventHandler的{​​{1}}内 或
e->Value = System::Drawing::Image::FromFile("c:/Test.jpeg");

答案 2 :(得分:0)

要获得更好的解决方案,请参阅此Blogspot帖子。

我为我的项目尝试了相同的解决方案,它运行良好,在我的datagrid单元格中显示16X16像素的图像,我编辑了上面TextandImageColumn类中的函数:

protected override void Paint(Graphics graphics, Rectangle clipBounds,
    Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
    object value, object formattedValue, string errorText,
    DataGridViewCellStyle cellStyle,
    DataGridViewAdvancedBorderStyle advancedBorderStyle,
    DataGridViewPaintParts paintParts)
    {
        // Paint the base content
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
           value, formattedValue, errorText, cellStyle,
           advancedBorderStyle, paintParts);

        if (this.Image != null)
        {
            PointF p = cellBounds.Location;
            p.X += 0;
            p.Y += 4;

            graphics.DrawImage(this.Image, p);
        }
    }
相关问题