Click here to Skip to main content
15,353,432 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
cmd.CommandText = "select_student";
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);
        pictureBox1.Image = null;
    MessageBox.Show("Record does not exixts");

can any body help me.

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

It looks like in your database you your image column
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]);

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

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: try not to use "magic numbers" for your code - it makes it hard to read and understand when you come back to maintain it.
are ok - ish - but
is not as readable as
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'
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