Ajmal Mughal
Ajmal Mughal

Reputation: 13

C# - How to handle picturebox from datagridview if database record is null

I am trying to get images from my datagridview and got success, but if some records dont have image or (null), than i got error ( Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.). Following is my code:

 private void dgridEmployees_SelectionChanged(object sender, EventArgs e)
    {
        DataGridViewCell cell = null;
        foreach (DataGridViewCell selectedCell in dgridEmployees.SelectedCells)
        {
            cell = selectedCell;
            break;

        }

        if (cell != null)
        {
            DataGridViewRow row = cell.OwningRow;
            lbl_ID.Text = row.Cells[0].Value.ToString();
            tboxEmployeeID.Text = row.Cells[1].Value.ToString();
            tboxEmployeeName.Text = row.Cells[2].Value.ToString();
            dtboxJoiningDate.Text = row.Cells[3].Value.ToString();
            tboxDepartment.Text = row.Cells[4].Value.ToString();
            tboxPath.Text = row.Cells[5].Value.ToString();

            byte[] img = (byte[])dgridEmployees.CurrentRow.Cells[6].Value;
            if (img == null)
                pictureBox1.Image = null;
            else
            {
                MemoryStream ms = new MemoryStream(img);
                pictureBox1.Image = Image.FromStream(ms);
            }


        }

Please suggest any solution for my above code?

Upvotes: 1

Views: 499

Answers (1)

Kapol
Kapol

Reputation: 6463

Firstly you need to check if the cell contains no value. In this case, it's value will be DBNull.Value (the single instance of the DBNull class). You can only convert its value to a byte[] if the comparison is false.

if (dgridEmployees.CurrentRow.Cells[6].Value != DBNull.Value)
{
    byte[] img = (byte[])dgridEmployees.CurrentRow.Cells[6].Value;
    MemoryStream ms = new MemoryStream(img);
    pictureBox1.Image = Image.FromStream(ms);
}
else
{
    pictureBox1.Image = null;
}

Upvotes: 1

Related Questions