1

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.

enter image description here

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);
               }
         }
      }
   }
}
2
  • Check for nulls by comparing the object-reference with DBNull.Value.
    – Dai
    Commented Jan 30, 2021 at 1:34
  • 1
    If you find an answer helpful, you can protect it (click on up arrow next to the answer), note that unlike accepting an answer, you can vote on any answer.
    – jmoreno
    Commented Jan 30, 2021 at 1:56

2 Answers 2

1

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.

0

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.