tags:

views:

94

answers:

3

I have a database with where boolean values are stored as bits (1 for true, 0 for false). What's the best way of converting these into .Net boolean values from a DataRow? Convert.ToBoolean doesn't seem to work.

+3  A: 
bool flag = (row[0]["Flag"] != DBNull.Value) ? (bool)row[0]["Flag"] : false;
Developer Art
If the db value is nullable shouldn't you then be using: bool? flag = (row[0]["Flag"] != DBNull.Value) ? (bool)row[0]["Flag"] : null; instead?
JohannesH
your code will not work JohannesH, you will get compile error
ArsenMkrt
@JohannesH: It is an option. Depends how nulls are handled in the application.
Developer Art
+1  A: 
bool flag = (row[0]["Flag"] != DBNull.Value) ? Convert.ToBoolean(row[0]["Flag"]) : false

should work. However you may want to think about how to treat the NULL value case as here it is deemed to be set to false which you may or not wish to be the case.

Dokie
+4  A: 

If the data type in the database is bit, then you don't have to do any conversion at all. The database driver automatically reads the values as booleans, all you have to do is to unbox the value:

bool value = (bool)row["field"];
Guffa
This is easily the most sensible solution.
Noldorin