简体   繁体   English

C#-如果数据库记录为空,如何从datagridview处理图片框

[英]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[]'.). 我试图从我的datagridview获取图像并获得成功,但是如果某些记录没有图像或(null),那么我得到了错误(无法将类型为'System.DBNull'的对象转换为类型为'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). 在这种情况下,它的值将是DBNull.ValueDBNull类的单个实例)。 You can only convert its value to a byte[] if the comparison is false. 如果比较为假,则只能将其值转换为byte[]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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