Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# convert bit to boolean

Tags:

c#

ado.net

I have a Microsoft SQL Server database that contains a data field of BIT type.

This field will have either 0 or 1 values to represent false and true.

I want when I retrieve the data to convert the value I got to false or true without using if-condition to convert the data to false if it is 0 or true if it is 1.

I'm wondering if there is a function in C# would do this direct by passing bit values to it?

like image 497
Eyla Avatar asked May 04 '10 17:05

Eyla


2 Answers

DataReader.GetBoolean(x) 

or

Convert.ToBoolean(DataRow[x]) 
like image 177
Robin Day Avatar answered Sep 18 '22 08:09

Robin Day


Depending on how are you performing the SQL queries it may depend. For example if you have a data reader you could directly read a boolean value:

using (var conn = new SqlConnection(ConnectionString)) using (var cmd = conn.CreateCommand()) {     conn.Open();     cmd.CommandText = "SELECT isset_field FROM sometable";     using (var reader = cmd.ExecuteReader())     {         while (reader.Read())         {             bool isSet = reader.GetBoolean(0);         }     } } 
like image 29
Darin Dimitrov Avatar answered Sep 21 '22 08:09

Darin Dimitrov