如何在datagridview单元格中显示URL中的图像?

时间:2012-05-25 18:41:05

标签: c# winforms datagridview

如何从URL加载图像然后将其放入DataGridView的单元格(而不是列标题)?包含图像的行将在运行时基于来自Web服务的搜索添加到视图中。无法找到针对此特定目的的答案......帮助!

首先我尝试使用PictureBox。当从Web服务接收事件时,我将循环到结果以添加行,每行包括一个图像。

// Add image
System.Windows.Forms.PictureBox picEventImage = new System.Windows.Forms.PictureBox();
picEventImage.Image = global::MyEventfulQuery.Properties.Resources.defaultImage;
picEventImage.ImageLocation = Event.ImageUrl;
this.dgvEventsView.Controls.Add(picEventImage);
picEventImage.Location = this.dgvEventsView.GetCellDisplayRectangle(1, i, true).Location;

即使图像加载完美,它看起来也与视图断开连接,即当我滚动时图像不会移动,而当用新数据刷新视图时,图像只是徘徊......糟糕。

所以我尝试了其他帖子的提示:

Image image = Image.FromFile(Event.ImageUrl);
DataGridViewImageCell imageCell = new DataGridViewImageCell();
imageCell.Value = image;
this.dgvEventsView[1, i] = imageCell;

但我说错了 “不支持URI格式。”

  • 我使用的图片不正确吗?
  • 我是否可以使用另一个类来代替图像?
  • 或者我别无选择,只能创建一个自定义控件(包含PictureBox)添加到DataGridView单元格中?

2 个答案:

答案 0 :(得分:3)

看一下这篇SO帖子https://stackoverflow.com/a/1906625/763026

 foreach (DataRow row in t.Rows)
    {
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(row["uri"].ToString());
                    myRequest.Method = "GET";
                    HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                    System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(myResponse.GetResponseStream());
                    myResponse.Close();

                    row["Img"] = bmp;
    }

答案 1 :(得分:-2)

这是我的解决方案。它可以正常地从DataGridView中检索图像以加载到PictureBox中。

表格活动:

 Private con As New SqlConnection("YourConnectionString")
    Private com As SqlCommand
Private Sub DGV_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DGV.CellClick
        con.Open()
        com = New SqlCommand("SELECT MyPhoto FROM tbGalary WHERE ID=" & DGV.Rows(e.RowIndex).Cells(0).Value, con)
        Dim ms As New MemoryStream(CType(com.ExecuteScalar, Byte()))
        txtPicture.Image = Image.FromStream(ms)
        txtPicture.SizeMode = PictureBoxSizeMode.StretchImage
        com.Dispose()
        con.Close()
End Sub

SQL表:

CREATE TABLE [dbo].[tbGalary](
    [ID] [int] NOT NULL,
    [MyPhoto] [image] NOT NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

SQL插入图片:

INSERT INTO tbGalary VALUES('1','D:\image1.jpg')
INSERT INTO tbGalary VALUES('2','D:\image2.jpg')
INSERT INTO tbGalary VALUES('3','D:\image3.jpg')
INSERT INTO tbGalary VALUES('4','D:\image4.jpg')
INSERT INTO tbGalary VALUES('5','D:\image5.jpg')

<强>结果

视频链接:Retrieve an image in DataGridView load to PictureBox in VB.NET