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

我在DataGridView上寻找这样的东西:

Image | Text | Text | Text | Image | Text 

基本上,我只想在同一行上的图像单元格和文本单元格。 我能够让它与不同类型的工作,例如:复选框,文本等…但我无法使它与图像一起工作。

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

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

在某些单元格中使用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类型,因此您无法使用相同的绑定。

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

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

DataGridViewCellFormattingEventHandler里面我分配了e->Value = System::Drawing::Image::FromFile("c:/Test.jpeg");
要么
e.Value = System.Drawing.Image.FromFile("c:/Test.jpeg");

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

我为我的项目尝试了相同的解决方案,它运行良好,在我的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; pX += 0; pY += 4; graphics.DrawImage(this.Image, p); } }