2012-07-14 155 views
6

我期待这样的事情上的DataGridView:C# - 的DataGridView - 图像和文本在同一行

Image | Text | 
Text | Text | 
Image | Text 

基本上,我只是想在同一行图像细胞和文本的单元格。 我能得到它与不同类型的工作,例如:复选框,文本,等.. 但我无法得到它与图像的工作。

我得到这个错误:Invalid Cast from 'System.String' to 'System.Drawing.Image'

有谁知道解决的办法还是对我应该怎么做这个建议? 谢谢

+1

发表您的ASPX标记这里 – 2012-07-14 04:48:31

+0

ref1c - 你是否在你的问题中得到行和列混淆?要对同一行的图片和文字(在不同的列)是微不足道的,只是有一个图像和文本列。有一个列和图像和文字是有点棘手。我现在正在为此做出答案。 – 2012-07-14 14:36:43

回答

7

在某些单元格中显示文本的列是相对容易的。

所有你需要做的是用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类型,因此不能使用相同的绑定。

也许你认为这样处理你自己的重写image列,但它是一些工作,可能无法支付本身与简单的设置值在您想直接文本的单元格。

+0

谢谢,男人!我尝试过不同的解决方案,但无法做到这一点,我忘了使用'DataGridViewTextBoxCell()'你的解决方案可以帮助我完成我的任务 – 2017-08-09 03:23:40

1

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

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

e.Value = System.Drawing.Image.FromFile("c:/Test.jpeg");

0

为了更好的解决方法,请参考本Blogspot职位。

我想为我的项目相同的解决方案,它运作良好,在我的DataGrid单元格显示16×16像素的图像,我已经编辑了以上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); 
     } 
    }