无法将类型为“System.String”的对象强制转换为“System.Byte []”。 [英] Unable to cast object of type 'System.String' to type 'System.Byte[]'.

查看:94
本文介绍了无法将类型为“System.String”的对象强制转换为“System.Byte []”。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从数据库中检索数据时,我收到以下错误

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



我的代码是

when i am retriving data from database i am getting following error
"Unable to cast object of type 'System.String' to type 'System.Byte[]'."

my code is

cmd.CommandText = "select_student";
cmd.Parameters.AddWithValue("@sno",textBox1.Text);
da = new SqlDataAdapter(cmd);
ds = new DataSet();
da.Fill(ds, "student");
if (ds.Tables[0].Rows.Count > 0)
{
    textBox2.Text = ds.Tables[0].Rows[0][0].ToString();
    textBox3.Text = ds.Tables[0].Rows[0][1].ToString();
    if (ds.Tables[0].Rows[0][2] != System.DBNull.Value)
    {
        byte[] data = (byte[])ds.Tables[0].Rows[0][2];
        ms = new MemoryStream(data);
        pictureBox1.Image = Image.FromStream(ms);
    }
    else
        pictureBox1.Image = null;
}
else
    MessageBox.Show("Record does not exixts");



任何人都可以帮助我。



仅限整洁的代码块 - OriginalGriff [/ edit]


can any body help me.

[edit]Tidy code block only - OriginalGriff[/edit]

推荐答案

在您的数据库中看起来像你的图像栏

(ds.Tables [0] .Rows [0 ] [2])

的数据类型为varchar而不是image(或varbinary(max))。

当你尝试将字符串(varchar)转换为字节数组时它会返回错误。

如果是这样则它将无效。



您必须更改图像列的数据类型进入正确的格式并再次尝试代码。
It looks like in your database you your image column
(ds.Tables[0].Rows[0][2])
has data type varchar rather than image(or varbinary(max)).
When you try to cast the string(varchar) into array of bytes it returns you the error.
If this is so it will not work.

You have to change the data type for the image column into the proper format and try the code again.


在这种情况下,简单的强制转换是不够的。



尝试:

A simple cast is not enough in this case.

Try :
byte[] data = System.Text.UTF8Encoding.GetBytes(ds.Tables[0].Rows[0][2]);





我用UTF8Encoding作为例子,用你需要的编码代替它。



干杯



I used UTF8Encoding as an example, substitute it wirh your needed encoding.

Cheers


如果您的数据库将该字段保存为NVCHA R或类似,那它确实是一个字符串。在这种情况下使用

If your database is holding the field as a NVCHAR or similar, then it is indeed a string. In which case use
string s = (string)ds.Tables[0].Rows[0][2];
byte[] data = System.Text.Encoding.ASCII.GetBytes(s);
ms = new MemoryStream(data);
pictureBox1.Image = Image.FromStream(ms);



BTW:尽量不要为代码使用魔术数字 - 这使得阅读起来很难并且当你回来维护它时明白。


BTW: try not to use "magic numbers" for your code - it makes it hard to read and understand when you come back to maintain it.

Tables[0]

Rows[0]

是好的 - 是 - 但是

are ok - ish - but

Rows[0][2]

的可读性不如

Rows[0]["DataStream"]


这篇关于无法将类型为“System.String”的对象强制转换为“System.Byte []”。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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