简体   繁体   中英

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?

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

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