Click here to Skip to main content
15,903,385 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
im trying to display image from database
Attachments
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";

            cn.Open();
            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);

            cn.Close();
Posted
Updated 29-Oct-19 0:44am

1 solution

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.
 
Share this answer
 
Comments
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900