【问题标题】:C# - How to handle picturebox from datagridview if database record is nullC# - 如果数据库记录为空,如何处理来自 datagridview 的图片框
【发布时间】:2015-12-29 11:35:39
【问题描述】:

我正在尝试从我的 datagridview 中获取图像并获得成功,但如果某些记录没有图像或(null),则出现错误(无法将“System.DBNull”类型的对象转换为“System.Byte” []'。)。以下是我的代码:

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


        }

请为我的上述代码提出任何解决方案?

【问题讨论】:

  • 你应该检查 System.DBNull.Value

标签: c#


【解决方案1】:

首先,您需要检查单元格是否不包含任何值。在这种情况下,它的值将是 DBNull.ValueDBNull 类的单个实例)。如果比较结果为假,您只能将其值转换为 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-11
    • 2011-05-05
    • 2018-01-06
    • 1970-01-01
    • 2019-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多