首页 > 解决方案 > 如何将图像从 DataGridView 显示到 PictureBox?

问题描述

我正在尝试在 PictureBox 中的 DataGridView 中显示图像。
我使用 SQL Server 作为数据库。

Me.PictureBox2.Image = DataGridView2.Item(10, i).Value

我想知道我正在使用什么代码。

这是错误说:

Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.

标签: sql-servervb.netwinformsdatagridviewbitmap

解决方案


您需要将 Blob 字段字节数组(现在是DataGridView单元格值)转换为Image对象。

MemoryStream可用于收集 Byte 数组并成为Image.FromStream()方法的Stream来源。

If DataGridView2(10, 1).Value Is Nothing Then Return
Using ms As MemoryStream = New MemoryStream(CType(DataGridView2(10, i).Value, Byte()))
    PictureBox2.Image?.Dispose()
    PictureBox2.Image = Image.FromStream(ms)
End Using

推荐阅读