Click here to Skip to main content
14,386,278 members
Rate this:
Please Sign up or sign in to vote.
See more:
im trying to display image from database
in picturebox but im getting error on
ImageByte = (byte[]) vcom.ExecuteScalar();
it say
Unable to cast object of type 'System.String' to type 'System.Byte[]'.

What I have tried:

            byte[] ImageByte = null;
            MemoryStream MemStream = null;
                     OleDbConnection cn = new OleDbConnection();
                     cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/ALL/Database7.accdb";

            OleDbCommand command = new OleDbCommand();
            command.Connection = cn;
            string sql = "select Attachments from Contacts where ID = 1";
        OleDbCommand vcom = new OleDbCommand(sql, cn);

ImageByte = (byte[]) vcom.ExecuteScalar();
    MemStream = new MemoryStream(ImageByte);
    pictureBox1.Image = Image.FromStream(MemStream);

Updated 29-Oct-19 1:44am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

The ExecuteScalar() method returns an object (in this case a string), and you cannot cast that to a byte[]. You need to accept the string and convert it to its original form. How is the Attachments column defined in your database? It should be a BLOB or similar to store a byte array.
Member 14630006 29-Oct-19 7:02am
Do You have any example?
Richard MacCutchan 29-Oct-19 7:15am
No, but Google will most likely find you one.
Member 14630006 29-Oct-19 7:16am
nah didnt found anything work
Richard MacCutchan 29-Oct-19 7:23am
If you want more help you need to show us the layout of your database. It is impossible to guess how you are storing your data.

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

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100