簡體   English   中英

如何修復異常:無法將“System.DBNull”類型的 object 轉換為“System.Byte []”類型

[英]How to fix exception:Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'

我有一個名為 tblStaff 的表,其中名為 staffImage 的列具有 Image 數據類型,允許存儲 Null。如果用戶提供他的照片,則此列將圖像存儲為二進制數據,如果他不提供他的圖像,則它將存儲 Null值。如果此列具有 null 值,則來自 Resource 文件夾的圖像應顯示在 pictureBox1 中,如果此列具有二進制數據,則作為二進制數據存儲在此列中的圖像應顯示在 pictureBox1 中。

CREATE TABLE tblStaff
(
    staffId int not null identity Primary Key,
    staffName varchar(50) not null,
    staffUserName varchar(25) not null,
    staffPassword varchar(30) not null,
    staffPhone varchar(15) not null,
    staffRole int not null,
    staffStatus tinyint not null,
    **staffImage image**
)

請參閱列名“staffImage”具有 IMAGE 數據類型

    ALTER PROC [dbo].[sp_GetStaffImage]
    @staffId varchar(150)
    as
    SELECT Stf.staffImage as 'Image' FROM tblStaff Stf WHERE 
    staffID=@staffId


.
.
.
.

string staffID = Convert.ToString(dataGridViewStaff.Rows[e.RowIndex].Cells["Staff Id"].Value);
..............
.............
..........
...........

SqlConnection con1 = new SqlConnection(cs);
con.Open();
SqlCommand cmd1 = new SqlCommand("sp_GetStaffImage", con);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("@staffId", staffID);
SqlDataAdapter sda1 = new SqlDataAdapter(cmd1);
DataSet ds = new DataSet();
sda1.Fill(ds);

if(ds.Tables[0].Rows.Count>0)
{
   var img = (byte[])ds.Tables[0].Rows[0][0];

   if (img != Null) //code if the data in column named staffImage is 
                    Binary data then show the image                        
                    in PictureBox1 from the database.
   {

         MemoryStream ms = new MemoryStream(img);
         pictureBox1.Image = new Bitmap(ms);
   }
   else  //code if the data in column named staffImage is Null then show the image in PictureBox1 
           from Resource folder .
   {
       pictureBox1.ImageLocation = "Resources/human.png";
   }

}
con.Close();

通過運行上面的代碼,我得到了如下異常:無法將“System.DBNull”類型的 object 轉換為“System.Byte []”類型。

無法將類型為“System.DBNull”的 object 轉換為類型“System.Byte []

您的異常源於以下調用:

 var img = (byte[])ds.Tables[0].Rows[0][0];

它是從這個發生的:

 ds.Tables[0].Rows[0][0] // This is DBNull, you can't cast it to byte[]

您正在嘗試將System.DBNull轉換為System.Byte[] ,但這是行不通的。 您需要先檢查此值,請參見下文。

注意:還有不止一種方法可以檢查這一點

 var img = ds.Tables[0].Rows[0][0] == DbNull.Value ? null : (byte[])ds.Tables[0].Rows[0][0];

@madreflection 建議的替代方法:

 var img = ds.Tables[0].Rows[0].Field<byte[]>(0);

“無法將'System.DBNull'類型的object類型轉換為xxx類型”的例外是正確的,它也非常簡單,因為您嘗試從DataRow轉換的列值是DbNull。

如果您從 DataTable 讀取行,則應始終檢查 DbNull(如果該列被鍵入為可空列)。

例如,代碼應該是這樣的:

 var img = (byte[])(ds.Tables[0].Rows[0][0] == DbNull.Value ? null : ds.Tables[0].Rows[0][0]);

作為替代答案,並且由於 SQL 服務器中的 IMAGE 列類型已被棄用,您可以使用 VARBINARY(MAX) NOT NULL 作為列類型並將默認值設置為 0x。

這樣,您將始終從查詢中至少返回 byte[0],而不必擔心 DBNull 檢查。

暫無
暫無

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

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