Click here to Skip to main content
15,797,721 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm a C# newbie working on a Winforms project and need help retrieving and displaying picture to picturebox. However, I'm getting an error
"Unable to Cast object of type String to type byte[]"
There are other elements such as Navigation that work well except for this.

What I have tried:

DataTable dt = new DataTable();             
dt = eda.NavigateEmployee(); // Create datatable from NavigateEmployee Class
tableBindings.DataSource = dt;

Binding picture = new Binding("Image", tableBindings, ((DataTable)tableBindings.DataSource).Columns[15].ColumnName);                
picture.Format += new ConvertEventHandler(pictureFormat);

private void pictureFormat(object sender, ConvertEventArgs e)
    byte[] b = (byte[])e.Value; // Error 'unable to cast object of type string to type byte[]
    MemoryStream ms = new MemoryStream(b);
    Bitmap bmp = new Bitmap(ms);
    e.Value = bmp;

// Function to save picture to SQL Server 
public byte[] ImageToStream(string fileName)
    MemoryStream stream = new MemoryStream();

        Bitmap image = new Bitmap(fileName);
        image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
    catch (Exception ex)
        MessageBox.Show(ex.Message, "Error Updating Photo", MessageBoxButtons.OK, MessageBoxIcon.Error);

    return stream.ToArray();

// Function to Display Selected Picture to PictureBox
public void UploadPicture() 
    OpenFileDialog ofd = new OpenFileDialog();
    ofd.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp)|*.jpg; *.jpeg; *.gif; *.bmp";

    if (ofd.ShowDialog() == DialogResult.OK) 
        strFilePath = ofd.FileName;
        EmployeePic.Image = new Bitmap(strFilePath);
        lblImageFilePath.Enabled = false;
        lblImageFilePath.Text = System.IO.Path.GetFileName(strFilePath).ToString();
Updated 18-Oct-22 8:02am
Richard Deeming 19-Oct-22 7:51am    
The data you're binding to is a string, not an array of bytes. You need to debug your code to find out what the column actually contains to see if there's any way to convert it to an image. We can't do that for you, as we have no access to your data.
f*rcklift2030 20-Oct-22 3:53am    
I have found the bug. There was a problem with sql query. Code works well now, Thanks!!

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