当我尝试从数据库中获取图像并绑定到datgridview时,我收到错误 [英] I have getting error when I am trying fetch images from database and bind to datgridview

查看:89
本文介绍了当我尝试从数据库中获取图像并绑定到datgridview时,我收到错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际上我首先尝试在数据库中保存图像,这部分我已经完成了,但是当我尝试从数据库中获取图像并将该图像绑定到datagridview时,这部分正在生成错误,如何解决这个问题,请帮助



我尝试过:



con.Open();

SqlDataReader dr = cmd.ExecuteReader();

if(dr.HasRows == true)

{

while(dr.Read())

{

byte [] bArray =(byte [])dr [image ;;

MemoryStream ms = new MemoryStream(bArray);

Image returnImage = Image.FromStream(ms);





}

}

con.Close();







byte [] bArray =(byte [])dr [image];此行显示错误

无法将System.String类型的对象强制转换为System.Byte []。

Actually first of all i am trying to save image in database , this part i have already done ,
but when i trying to fetch image from database and bind that image to datagridview this part is generating error, how to solve this problem, pls help

What I have tried:

con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
while (dr.Read())
{
byte[] bArray = (byte[])dr["image"];
MemoryStream ms = new MemoryStream(bArray);
Image returnImage = Image.FromStream(ms);


}
}
con.Close();



byte[] bArray = (byte[])dr["image"]; this line show error
Unable to cast object of type 'System.String' to type 'System.Byte[]'.

推荐答案

错误说的是你可以将字符串转换为字节数组 - 这意味着数据库中的列是VARCHAR或NVARCHAR字段而不是VARBINARY或BLOB

这意味着其中一个两件事:

1)你根本没有存储实际的图像数据。



2)你把它存储为BASE64字符串或类似字符串。



如果没有您用来保存它的代码,我们无法分辨哪个 - 但是从上面的代码中,我怀疑第一个和你保存了字符串连接的图像。

看看这个:为什么我得到参数无效。我从数据库中读取图像时出现异常? [ ^ ]它会告诉您最有可能出现的问题,以及如何绕过它。
What the error says is that you can;t convert a string to a byte array - which means that the column in your database is a VARCHAR or NVARCHAR field instead of a VARBINARY or BLOB
Which means one of two things:
1) You haven't stored the actual image data at all.
Or
2) You've stored it as a BASE64 string or similar.

Without the code you used to save it, we can't tell which - but from your code above, I'd suspect the first and that you "saved" the image by string concatenation.
Have a look at this: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] It shows you what the problem most likely is, and how to get round it.


这篇关于当我尝试从数据库中获取图像并绑定到datgridview时,我收到错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆