Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a bit value with SqlDataReader and convert it to bool?

Tags:

I am retrieving user information from a database using a simple query.

select * from dbo.[User] u where u.Email = @email 

I then try to get the value of a column, called IsConfirmed (which is represented as a bit type column in the database) and convert it to bool.

bool isConfirmed = int.Parse(sqlDataReader["IsConfirmed"].ToString()) == 1; 

I then get an FormatException error, stating that "Input string was not in a correct format.".

I saw a similar question with an answer providing this code:

bool isConfirmed = sqlDataReader.GetBoolean(0); 

But this won't work with my case, because I don't know the index of the IsConfirmed column and I don't want to know it. I want to use the column name.

like image 673
Yulian Avatar asked Jun 07 '14 13:06

Yulian


1 Answers

The value returned from the data reader indexer property is of type object but can be cast to the data type it has been stored as.

Try this:

bool isConfirmed = (bool)sqlDataReader["IsConfirmed"] 
like image 124
Slade Avatar answered Oct 23 '22 12:10

Slade