繁体   English   中英

无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。 错误

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

到目前为止,这就是我从数据库中将图像放入picturebox1所做的工作,但现在我收到此错误:

无法将System.DBNull类型的对象转换为System.Byte[]类型。

此平台上已有的解决方案不起作用。

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;
}

检查使用这个:

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

您也可以添加一些其他验证:

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

很高兴为您服务!

将您的代码更改为:

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;
        }

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM