如果其值为 null,则将图像从数据库加载到 windows 表单
Loading an image from a database into a windows form if its value is null
双击此 windows 表单中包含的数据网格对象中的数据时,会出现辅助表单,以便可以编辑数据库。
但是,如果数据库中当前没有存储图像(其值为空),则会出现以下异常:
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);
}
}
}
}
}
像这样:
Object imageOrDBNull = row["Image"];
if( imageOrDBNull == DBNull.Value ) {
// ...
}
else if( imageOrDBNull is Byte[] bytes ) {
Image current = this.IdPictureBox.Image;
if( current != null ) {
this.IdPictureBox.Image = null;
current.Dispose();
current = null;
}
try
{
this.IdPictureBox.Image = Image.FromStream( new MemoryStream( bytes, writable: false ) );
}
catch( Exception ex )
{
// TODO: Error handling.
}
}
else {
throw new InvalidOperationException( "Expected DBNull or Byte[], but encountered " + ( imageOrDBNUll?.GetType() ?? "null" ) + " instead." );
}
这是一个常见问题,解决方法很简单——先看看是什么问题。
这样做有多种方式,我喜欢创建通用扩展方法,但对您的情况来说最简单的方法可能是使用 MS class DataRowExtensions
var pic = row.Field<byte[]>(“Image”); //<-- where the exception occurs
您必须包含 DataRowExtensions,仅此而已。
双击此 windows 表单中包含的数据网格对象中的数据时,会出现辅助表单,以便可以编辑数据库。
但是,如果数据库中当前没有存储图像(其值为空),则会出现以下异常:
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);
}
}
}
}
}
像这样:
Object imageOrDBNull = row["Image"];
if( imageOrDBNull == DBNull.Value ) {
// ...
}
else if( imageOrDBNull is Byte[] bytes ) {
Image current = this.IdPictureBox.Image;
if( current != null ) {
this.IdPictureBox.Image = null;
current.Dispose();
current = null;
}
try
{
this.IdPictureBox.Image = Image.FromStream( new MemoryStream( bytes, writable: false ) );
}
catch( Exception ex )
{
// TODO: Error handling.
}
}
else {
throw new InvalidOperationException( "Expected DBNull or Byte[], but encountered " + ( imageOrDBNUll?.GetType() ?? "null" ) + " instead." );
}
这是一个常见问题,解决方法很简单——先看看是什么问题。
这样做有多种方式,我喜欢创建通用扩展方法,但对您的情况来说最简单的方法可能是使用 MS class DataRowExtensions
var pic = row.Field<byte[]>(“Image”); //<-- where the exception occurs
您必须包含 DataRowExtensions,仅此而已。