VB.NET如何将SQL Server存储的图片赋值给Button并解决类型转换报错
错误原因
数据库中的Image类型字段存储的是二进制字节数组(System.Byte[]),无法直接强制转换为System.Drawing.Image类型,需要先将字节数组转换为内存流,再从内存流生成Image对象。
修改后的代码
Dim strsql As String Dim ImgSQl As Image Dim imgBytes As Byte() ' 新增变量存储读取到的二进制字节 Dim con As New SqlConnection("constring") con.Open() strsql = "SELECT Image FROM Inventory WHERE ID=@ID" Dim cmd As New SqlCommand(strsql, con) ItemID = 1 cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = ItemID Dim myreader As SqlDataReader myreader = cmd.ExecuteReader If myreader.Read() Then ' 增加判断避免无数据时报错 ' 先读取字节数组 imgBytes = DirectCast(myreader("Image"), Byte()) ' 将字节数组转为内存流,再生成Image对象 Using ms As New System.IO.MemoryStream(imgBytes) ImgSQl = Image.FromStream(ms) End Using End If con.Close() btn1.Image = ImgSQl
注意事项
- 代码中增加了
myreader.Read()的存在性判断,避免查询无匹配数据时触发空引用错误 - 需要确保项目中已经引用了
System.Drawing程序集,否则Image.FromStream方法无法正常调用 - 若你使用的是.NET Core 3.0+ / .NET 5+ 版本,需要先安装NuGet包
System.Drawing.Common才能使用System.Drawing相关类 - 如果数据库中
Image字段允许为空,需要额外加空值判断,避免转换字节数组时报错
内容的提问来源于stack exchange,提问作者jumexmango
相关产品推荐
相关产品推荐

