我想在我的Windows窗体中加载图像(存储在图像类型的sql server中)有时下面的代码工作正常但是在更新我的数据库之后加载我的表单后我得到了以下错误
无法将'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();
}
任何机构都可以提到我缺少什么或做什么?
提前致谢
答案 0 :(得分: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();
}
希望这会有所帮助......