【发布时间】:2021-05-03 22:06:14
【问题描述】:
当双击此窗体中包含的此数据网格对象中包含的数据时,会出现一个辅助窗体,以便可以编辑数据库。
但是,如果数据库中当前没有存储图像(其值为空),则会发生以下异常:
System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.'
纠正代码以使图像正确加载到其对应的图片框的最佳方法是什么? 这是发生异常的部分代码。
private void StudentForm_Load(object sender, EventArgs e)
{
//For Update Process
if (this.IsUpdate == true)
{
using (SqlConnection con = new SqlConnection(AppConnection.GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("usp_Students_ReloadDataForUpdate", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@StudentName", this.StudentName);
if (con.State != ConnectionState.Open)
con.Open();
DataTable dtStudent = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dtStudent.Load(sdr);
DataRow row = dtStudent.Rows[0];
StudentNameTextBox.Text = row["StudentName"].ToString();
AgeTextBox.Text = row["Age"].ToString();
GenderTextBox.Text = row["Gender"].ToString();
DescriptionTextBox.Text = row["Description"].ToString();
var pic = (byte[])row["Image"]; //<-- where the exception occurs
if (pic != null)
{
MemoryStream ms = new MemoryStream(pic);
IdPictureBox.Image = Image.FromStream(ms);
}
}
}
}
}
【问题讨论】:
-
通过比较对象引用和
DBNull.Value来检查空值。 -
如果您发现某个答案有帮助,您可以保护它(点击答案旁边的向上箭头),请注意,与接受答案不同,您可以对任何答案进行投票。
标签: c# sql visual-studio picturebox