无法将数据库从数据库加载到c#中的图片框中

时间:2017-05-18 16:28:48

标签: c# visual-studio

您好我正在尝试从数据库中检索图像(jpg)并将其设置为图片框,我收到错误消息:“System.ArgumentException:'参数无效。'”。可以帮我查一下如何避免这种异常或如何解决问题?谢谢,下面你有代码。

         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();

1 个答案:

答案 0 :(得分:1)

您需要使用从数据库收到的byte [] ms构建MemoryStream a

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