user7127000
user7127000

Reputation: 3243

Converting SQL data type BIT NOT NULL to C# type Byte through a SqlDataReader

I have a simple piece of code

bool retrievalAttempted = Convert.ToBoolean(reader.GetByte(1));

where column 1 is of type BIT NOT NULL and yet I keep getting the exception

System.InvalidCastException: Specified cast is not valid.

What am I doing wrong here?

Upvotes: 1

Views: 623

Answers (2)

Davidet
Davidet

Reputation: 3

A bit is different than a byte !

Look at this link for sql server types vs .net types SQL Server Data Type Mappings

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

If it's a bit-column you have to use reader.GetBoolean:

bool retrievalAttempted = reader.GetBoolean(1);

SQL Server Data Type Mappings

bit       Boolean       Bit       GetSqlBoolean       Boolean       GetBoolean

GetByte is only used for tinyint-columns.

Upvotes: 6

Related Questions