-5

Until now, this is what I've done to place an image in picturebox1 from a database, but now I'm getting this error:

Unable to cast object of type System.DBNull to type System.Byte[].

The already available solutions from this platform didn't work.

Image img;
byte[] bytimg = (byte[])dt.Rows[0]["Picture"];

//convert byte of imagedate to Image format
using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
{
    ms.Write(bytimg, 0, bytimg.Length);

    img = Image.FromStream(ms, true);

    pictureBox1.Image = img;
}
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
sudip
  • 85
  • 2
  • 10
  • Check if `dt.Rows[0]["Picture"]` is null first. – Blue Nov 09 '15 at 21:40
  • Consider checking this answer as well here: http://stackoverflow.com/questions/870697/unable-to-cast-object-of-type-system-dbnull-to-type-system-string – Blue Nov 09 '15 at 21:41
  • The error is pretty clear. You can't cast a null value to a byte array. Check if the value is null before trying to cast it. – David Nov 09 '15 at 21:44
  • check `if(dt.Rows[0]["Picture"] == null){ return} else` you need to wrap the using around the Else otherwise you will still get errors – MethodMan Nov 09 '15 at 21:49

2 Answers2

4

Check using this:

if(dt.Rows[0]["Picture"] != System.DBNull.Value)
{
   ...
}

You can add a some other validations too:

if(dt != null && dt.Rows != null && dt.Rows.Count > 0
   && dt.Rows[0]["Picture"] != System.DBNull.Value)
{
   ...
}

Happy to Help you!

Igor Quirino
  • 1,187
  • 13
  • 28
0

Change your code to:

Image img;

if(dt.Rows[0] != System.DBNull.Value)
{

    byte[] bytimg = (byte[])dt.Rows[0]["Picture"];

    //convert byte of imagedate to Image format
    using (MemoryStream ms = new MemoryStream(bytimg, 0, bytimg.Length))
    {

        ms.Write(bytimg, 0, bytimg.Length);

        img = Image.FromStream(ms, true);

        if (img != null)
        {
            pictureBox1.Image = img;
        }

    }

}
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64
  • you're a little bit off here.. the issue is in this line `byte[] bytimg = (byte[])dt.Rows[0]["Picture"];` can't cast a `null to a byte[]` this is definitely not an answer.. – MethodMan Nov 09 '15 at 21:50