简体   繁体   中英

Loading an image from a database into a windows form if its value is null

When doubling clicking the data contained within this datagrid object contained in this windows form, a secondary form appears so that the database can be edited.

在此处输入图像描述

However if there is no image currently stored in the database (its value is null) the following exception occurs:

System.InvalidCastException: 'Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.'

What is the best way correct the code so that the image loads into its correspond picturebox properly? This is part of the code where the exception occurs.

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);
               }
         }
      }
   }
}

This is a common problem, the solution is easy — check to see what it is first.

There are various was of doing so, I like to create generic extension methods, but the simplest for your case is probably to use the MS class DataRowExtensions

var pic = row.Field<byte[]>(“Image”); //<-- where the exception occurs

You'll have to include the DataRowExtensions, but that's it.

Like this:

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." );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM