user10249871
user10249871

Reputation:

get byte array from datatable to list c#

I gave a byte[] stored in database,

I get the byte array in my DataTable from sql

Image

this is my DataTable, System.byte[] is my image in bytes which is stored in my datatbase

now I want to convert this DataTable into list

this is my current Code

var answerList = (from rw in dt.AsEnumerable()
                    select new RegistrationAnswers()
                    {
                        responseID = rw["responseID"].ToString() == string.Empty ? 0 : Convert.ToInt32(rw["responseID"].ToString()),
                        responseRegID = rw["responseRegID"].ToString() == string.Empty ? 0 : Convert.ToInt32(rw["responseRegID"].ToString()), 
                        responseAnswer = rw["responseAnswer"].ToString(),
                        _ResponseDocument =  rw["responseDocument"], //here i want to validate if rw["responseDocument"] is null or not and if this is not null then assign the byte[] data to _ResponseDocument 
                        formID=Convert.ToInt32(rw["formID"])
                    }).ToList();

when I updated my code to

//At top
byte[] tempByteArray = new byte[0];

_responseDocument = Convert.IsDBNull((byte[])rw["responseDocument"]) == false ? tempByteArray : (byte[])rw["responseDocument"],

I am getting following error

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

i want to validate if rw["responseDocument"] is null or not and if this is not null then assign the byte[] data to _ResponseDocument

Upvotes: 3

Views: 4616

Answers (2)

user6656728
user6656728

Reputation:

I faced the same problem while getting the data from DataTable into list

what I did is created a byte array in the method

byte[] tempByteArray = new byte[0];

and in my loop did something like this

_responseDocument = rw["responseDocument"].ToString() == "" ? tempByteArray : (byte[])rw["responseDocument"],

Upvotes: 0

selami
selami

Reputation: 2498

Try casting

rw["responseDocument"] == System.DBNull.Value ? new byte[0] : (byte[])rw["responseDocument"];

or

Convert.IsDBNull(rw["responseDocument"]) ? new byte[0] : (byte[])rw["responseDocument"];

Upvotes: 2

Related Questions