Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlDataReader Reading a bit datatype from SQL Server 2008?

I am using SQL Server 2008 in a asp.net/c# program. I am trying to use SqlDataReader to fetch the data form the db, but I'm not sure what to use for the datatype "bit".

//these are the assemblies i added manually
using System.Web.Script.Services;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

SqlConnection conn2 = new SqlConnection(ConfigurationManager.ConnectionStrings["ucsConnectionString"].ConnectionString);
SqlDataReader rdr2 = null;
conn2.Open();

SqlCommand cmder = new SqlCommand("usp_Device_GetBy_DeviceID", conn2);
cmder.Parameters.AddWithValue("@ID", id);
cmder.CommandType = CommandType.StoredProcedure;
rdr2 = cmder.ExecuteReader();
rdr2.Read();

*insert datatype & var* = rdr2.GetSqlBit(rdr2.GetOrdinal("Line_Name"));

I found a couple sites that referenced the above "GetSqlBit" but apparently it is not part of the assemblies I'm using. Any suggestions how I can read this "bit" datatype from SQL?

I found a similar datatype using "GetSqlBinary" but I don't fully understand how it works or if it would be appropriate for this situation?

Everyone's ongoing help is appreciated!

like image 895
ImGreg Avatar asked Jul 13 '11 15:07

ImGreg


2 Answers

A bool is what you are looking for. Depending on whether the database table allows a null value, it will be bool or bool? for a nullable type.

(if the bit column allows nulls -- many ways you can do this)

bitValue = reader["MyBitColumn"] as bool? ?? null;

if not, then:

bitValue = (bool)reader["MyBitColumn"];
like image 70
Bryan Crosby Avatar answered Oct 14 '22 04:10

Bryan Crosby


A bit stored in a database can actually have three states, not just two: 0, 1, and NULL. For this reason, the type you want is a Nullable<bool>, or the bool? shorthand.

However, it looks like you want the .GetBoolean() method. That method requires you to check for null before calling the method. The code might look like this:

bool? Line_Name = rdr2.IsDBNull(rdr2.GetOrdinal("Line_Name"))?null:rdr2.GetBoolean(rdr2.GetOrdinal("Line_Name"));
if (Line_Name != null && Line_Name.Value)
{
    //...
}
like image 41
Joel Coehoorn Avatar answered Oct 14 '22 03:10

Joel Coehoorn