tags:

views:

303

answers:

4

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?

+2  A: 

Use the GetSqlBoolean method.

Update

Make sure you cast your return value as a boolean i.e.

var active = (bool)rdr.GetSqlBoolean(5);
James
If you are going to downvote please specify why? Makes no sense to downvote an answer without giving a reason...
James
`SqlBoolean` is effectively just a wrapper around a boolean to allow for nullability etc. So if you're going to call `GetSqlBoolean` and then immediately cast the result to `bool` you might as well just call `rdr.GetBoolean` in the first place.
LukeH
A: 

use GetFieldType to determine that data type to use.

fizch
A: 

Thx for the help, my final code became:

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

On a sidenote, why can't I vote for an answer to be correct?

Jorn
You shouldn't need to use GetOrdinal, the GetSqlBoolean should be sufficient. They both have the same return type...
James
You can't upvote on StackOverflow until you have... 15? reputation points, which you earn by getting upvotes yourself, selected answers, and badges. I think you should be able to mark a particular answer as the chosen answer, however.
Matt Hamsmith
`SqlBoolean` is effectively just a wrapper around a boolean to allow for nullability etc. So if you're going to call `GetSqlBoolean` and then immediately cast the result to `bool` you might as well just call `rdr.GetBoolean` in the first place.
LukeH
+1  A: 

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);
LukeH