Getting bits from SqlServer in C #

I need to get a bit from sql server in C #. I tried different solutions, for example:

bool active = rdr.GetSqlBinary(5);
Int16 active = rdr.GetSqlBinary(5);

But cannot find a way to get the bit. Can someone give an example?

+5
source share
5 answers

If you are sure that the column values ​​will never be NULL, then the following will do the trick:

bool active = rdr.GetBoolean(rdr.GetOrdinal("Active"));

If it is possible that values NULLcan be returned:

int oActive = rdr.GetOrdinal("Active");
bool? active = rdr.IsDBNull(oActive) ? (bool?)null : rdr.GetBoolean(oActive);
+12
source

Use the GetSqlBoolean method .

Refresh

Make sure you select the return value as logical ie

var active = (bool)rdr.GetSqlBoolean(5);
+4
source

GetFieldType, , .

0

, :

bool active = (bool)rdr.GetSqlBoolean(rdr.GetOrdinal("Active"));
0

There is a public get method for the SqlBoolean: IsTrue structure. Thus, you can use it in such a way as to make sure that the result is boolean:

bool active = rdr.GetSqlBoolean(5).IsTrue;
0
source

All Articles