Reputation: 227
I need to get a Bit from a sql server into c#. I tried differnt solutions like:
bool active = rdr.GetSqlBinary(5);
Int16 active = rdr.GetSqlBinary(5);
But can't find any way to get the Bit. Can someone give an example?
Upvotes: 7
Views: 23621
Reputation: 71
There is a public get method of SqlBoolean struct: IsTrue. So you can use it this way, to be sure that result is boolean:
bool active = rdr.GetSqlBoolean(5).IsTrue;
Upvotes: 0
Reputation: 227
I arrived at the following solution using:
bool active = (bool)rdr.GetSqlBoolean(rdr.GetOrdinal("Active"));
Upvotes: 0
Reputation: 269658
If you're certain that the column values will never be NULL
then the following will do the trick:
bool active = rdr.GetBoolean(rdr.GetOrdinal("Active"));
If it's possible that NULL
values might be returned:
int oActive = rdr.GetOrdinal("Active");
bool? active = rdr.IsDBNull(oActive) ? (bool?)null : rdr.GetBoolean(oActive);
Upvotes: 13
Reputation: 82136
Use the GetSqlBoolean method.
Update
Make sure you cast your return value as a boolean i.e.
var active = (bool)rdr.GetSqlBoolean(5);
Upvotes: 6