【问题标题】:Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'. error无法将“System.DBNull”类型的对象转换为“System.Byte[]”类型。错误
【发布时间】:2015-11-09 21:39:53
【问题描述】:

到现在为止,这是我从数据库中将图像放入 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;
}

【问题讨论】:

  • 先检查dt.Rows[0]["Picture"]是否为空。
  • 考虑在此处也检查此答案:stackoverflow.com/questions/870697/…
  • 错误很明显。您不能将空值强制转换为字节数组。在尝试强制转换之前检查该值是否为空。
  • 检查 if(dt.Rows[0]["Picture"] == null){ return} else 你需要将 using 包裹在 Else 周围,否则你仍然会得到错误

标签: c# winforms


【解决方案1】:

用这个检查:

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)
{
   ...
}

很高兴为您提供帮助!

【讨论】:

    【解决方案2】:

    将您的代码更改为:

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

    【讨论】:

    • 你有点离题了.. 问题出在这一行 byte[] bytimg = (byte[])dt.Rows[0]["Picture"]; can't cast a null to a byte[] 这绝对不是答案..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多