c# - 如果图像的值为空,则将图像从数据库加载到 Windows 窗体中
问题描述
当双击包含在此 windows 窗体中的此 datagrid 对象中的数据时,将出现一个辅助窗体,以便可以编辑数据库。
但是,如果数据库中当前没有存储图像(其值为 null),则会发生以下异常:
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);
}
}
}
}
}
解决方案
这是一个常见问题,解决方案很简单——首先检查一下它是什么。
这样做有多种方法,我喜欢创建通用扩展方法,但最简单的情况可能是使用 MS 类 DataRowExtensions
var pic = row.Field<byte[]>(“Image”); //<-- where the exception occurs
您必须包含 DataRowExtensions,仅此而已。
推荐阅读
- c# - .NET 在什么情况下决定取消 PLINQ 任务?
- symfony - 请求返回 IRI 而不是嵌套关系中的对象
- java - 在MongoDB中存储一些大于16MB的文档的策略
- javascript - ReactJS 状态自行重置
- selenium - 如何通过包含大括号的类名来识别元素
- dynamics-crm - 获取包含在 Dynamics 365 电子邮件工作流中的记录 URL(动态)中的 appid
- php - laravel 中所有路由的默认视图
- java - 使用 time square 获取两个选定的入住和退房日期
- postgresql - 如何通过添加所有可用行的日期来查询 PostgreSQL 以获取总时间?
- java - 计算Java句子中给定字母的出现次数