0

I have a column value in Hash format in db and column datatype is varbinary(8000).I convert it into byte array.

Problem is some time this column value has null value,now in my code I want to check if column value has null value then return default value of byte array,otherwise return column value using following code

 objUser.Password_Hash = IIf(reader("Password_Hash") Is Nothing, {}, reader("Password_Hash"))

this gives error as below

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

1 Answer 1

1

Firstly, don't use IIf in VB unless you're using a version so old that that the If operator doesn't exist. I think that that would mean VB 2005.

Secondly, a NULL value from a database is not Nothing in VB. It is actually an object, specifically an instance of the DBNull class, represented by the DBNull.Value field.

Thirdly, while you can compare directly to DBNull.Value if required, data readers and DataRows actually have methods dedicated specifically to testing for NULL.

So, putting it all together:

objUser.Password_Hash = If(reader.IsDBNull(reader.GetOrdinal("Password_Hash")),
                           New Byte() {},
                           DirectCast(reader("Password_Hash"), Byte()))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.