Search code examples
c#booleanbitsqldatareader

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


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.


Solution

  • 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"]