Click here to Skip to main content
15,880,651 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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
C#
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");

can any body help me.

[edit]Tidy code block only - OriginalGriff[/edit]
Posted
Updated 13-Nov-10 0:05am
v2

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.
 
Share this answer
 
A simple cast is not enough in this case.

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


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

Cheers
 
Share this answer
 
If your database is holding the field as a NVCHAR or similar, then it is indeed a string. In which case use
C#
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: 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]
and
Rows[0]
are ok - ish - but
Rows[0][2]
is not as readable as
Rows[0]["DataStream"]
 
Share this answer
 
If my database is holding the field blob,then what should i do in that case..because I am getting the error as 'unable to cast object of type system.dbnull to system.byte'
 
Share this answer
 
Comments
VICK 28-Mar-14 7:35am    
Do post a new question to get proper help. as Already solved questions have minor chances of focus. :)
VICK 28-Mar-14 7:35am    
Ah.. New CP Modification. I can reply to My OWN comment. :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900