user1358072
user1358072

Reputation: 447

How to handle null value in byte[]

I have binary images in the Image column of my database table, but there are some null values in the Image column. So an exception is thrown at,

byte[] data = (byte[])ds.Tables[0].Rows[0][0]` because of null.

How to handle this?

Exception message,

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

My code,

using (var sqlConn = new SqlConnection(connstr))
{
    sqlConn.Open();
    ds = new DataSet();

    SqlDataAdapter sqa = new SqlDataAdapter("Select Image from Templates where Shoe='" + selectedShoe + "'", sqlConn);

    sqa.Fill(ds);

    //i got error here
    byte[] data = (byte[])ds.Tables[0].Rows[0][0];

    .....

Upvotes: 2

Views: 23365

Answers (2)

Chad Stellrecht
Chad Stellrecht

Reputation: 21

Handling nulls at the SQL query worked for me. If your Image column is null, the ISNULL() function will return your next value (0 in this example).

SqlDataAdapter sqa = new SqlDataAdapter("SELECT ISNULL([Image],0) AS Image FROM Templates where Shoe='" + selectedShoe + "'", sqlConn);

Upvotes: 2

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

You need to specifically check for DBNull in that column before attempting the cast:

byte[] data = null;
if (!ds.Tables[0].Rows[0].IsNull(0))
    data = (byte[])ds.Tables[0].Rows[0][0];

Note that this will fail with the same type of exception if the column in question does in fact not contain a byte array.

Upvotes: 8

Related Questions