簡體   English   中英

C#-如果數據庫記錄為空,如何從datagridview處理圖片框

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

我試圖從我的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);
            }


        }

請為我上面的代碼提出任何解決方案?

首先,您需要檢查單元格是否不包含任何值。 在這種情況下,它的值將是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM