user3720015
user3720015

Reputation:

Can't load Image from Database into a picturebox in c#

Hello I am trying to retrieve an image(jpg) from database and set it to a picturebox and I am getting the error message :"System.ArgumentException: 'Parameter is not valid.'" .Can some1 help me to figure out how to avoid this exception or how to fix the issue?Thank you, below you have the code.

         con.Open();
        cmd.CommandText = "SELECT Imagine FROM Filme WHERE Id=@Id";
        cmd.Parameters.Add(new SqlParameter("Id", id));
         //the id is an int and is initialized previously.
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        SqlCommandBuilder bd = new SqlCommandBuilder(da);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        byte[] a = (byte[])(ds.Tables[0].Rows[0]["Imagine"]);
        MemoryStream ms = new MemoryStream();
        pictureBox2.Image = Image.FromStream(ms);

        pictureBox2.SizeMode = PictureBoxSizeMode.StretchImage;
        pictureBox2.BorderStyle = BorderStyle.Fixed3D;
        ms.Close();

Upvotes: 0

Views: 165

Answers (1)

Veera Induvasi
Veera Induvasi

Reputation: 822

You need to construct your MemoryStream ms using the byte[] a you received from the database:

byte[] a = (byte[])(ds.Tables[0].Rows[0]["Imagine"]);
MemoryStream ms = new MemoryStream(a);
pictureBox2.Image = Image.FromStream(ms);
ms.Close();

Upvotes: 1

Related Questions