如何在数据网格视图单元格中显示来自 URL 的图像

本文关键字:显示 URL 图像 单元格 数据 数据网 视图 网格 | 更新日期: 2023-09-27 18:35:18

如何从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 格式。"

  • 我是否错误地使用图像?
  • 是否有另一个类可用于 URL 图像而不是图像?
  • 还是我别无选择,只能创建一个自定义控件(其中包含一个 PictureBox)以添加到 DataGridView 单元格?

如何在数据网格视图单元格中显示来自 URL 的图像

看看这个 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;
    }
这是我

的解决方案。对我来说,从数据网格视图中检索图像以加载到图片框中可以正常工作。

表单事件:

 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')

结果

视频链接:在 DataGridView 中检索图像加载到 VB.NET 中的图片框