2015-06-05 61 views
0

我想在我的窗体窗体中加载图像(存储在图像类型的sql服务器中)有时下面的代码工作正常,但是在更新我的数据库和加载我的表单后,出现以下错误在图片框c中加载图片时出现错误#

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

我的代码正在为:

 cmd = new SqlCommand("sp_atnd_detail",conn); 
     cmd.CommandType = CommandType.StoredProcedure; 
     cmd.Parameters.AddWithValue("@userid", Login.userid); 
     ad = new SqlDataAdapter(cmd); 
     ds = new DataSet(); 
     ad.Fill(ds,0,0,"vw_EmpAtnd"); 
     gvDetail.DataSource = ds.Tables["vw_EmpAtnd"]; 
     conn.Open(); 
     dr = cmd.ExecuteReader(); 
     if (dr.Read()) 
     { 
      txtName.Text = dr["Employee"].ToString(); 
      txtNic.Text = dr["NIC"].ToString(); 
      txtUserName.Text = dr["UserName"].ToString(); 
      txtRole.Text = dr["Role"].ToString(); 
      byte[] Img = (byte[])dr["Pic"]; 
      MemoryStream ms = new MemoryStream(Img); 
      picEmp.Image = Image.FromStream(ms); 
      picEmp.Refresh(); 
      conn.Close(); 
      dr.Close(); 
     } 

任何机构可以提我缺少什么或做什么?

在此先感谢

回答

1

因为你想投一个空场。即,pic字段可能不适用于表中的某些员工记录。因此,尝试铸造它,像之前检查现场,

cmd = new SqlCommand("sp_atnd_detail",conn); 
    cmd.CommandType = CommandType.StoredProcedure; 
    cmd.Parameters.AddWithValue("@userid", Login.userid); 
    ad = new SqlDataAdapter(cmd); 
    ds = new DataSet(); 
    ad.Fill(ds,0,0,"vw_EmpAtnd"); 
    gvDetail.DataSource = ds.Tables["vw_EmpAtnd"]; 
    conn.Open(); 
    dr = cmd.ExecuteReader(); 
    if (dr.Read()) 
    { 
     txtName.Text = dr["Employee"].ToString(); 
     txtNic.Text = dr["NIC"].ToString(); 
     txtUserName.Text = dr["UserName"].ToString(); 
     txtRole.Text = dr["Role"].ToString(); 
     if (!dr.IsDBNull(dr.GetOrdinal("Pic"))) 
     { 
      byte[] Img = (byte[])dr["Pic"]; 
      MemoryStream ms = new MemoryStream(Img); 
      picEmp.Image = Image.FromStream(ms); 
      picEmp.Refresh(); 
     } 
     conn.Close(); 
     dr.Close(); 
    } 

希望这有助于...

+0

非常感谢你..它的工作原理 – Waqas