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
2009-08-26 10:50:29
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
2009-08-26 11:00:21
your code will not work JohannesH, you will get compile error
ArsenMkrt
2009-08-26 11:09:05
@JohannesH: It is an option. Depends how nulls are handled in the application.
Developer Art
2009-08-26 11:09:51
+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
2009-08-26 11:03:09
+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
2009-08-26 11:03:17