开发者

C# convert bit to boolean

开发者 https://www.devze.com 2022-12-29 07:15 出处:网络
I have a Microsoft SQL Server database that contains a data field of BIT type. This field will have either 0 or 1 values to represent false and true.

I have a Microsoft SQL Server database that contains a data field of BIT type.

This field will have either 0 or 1 values to represent false and true.

I want when I retrieve the data to convert the value I got to fals开发者_开发百科e or true without using if-condition to convert the data to false if it is 0 or true if it is 1.

I'm wondering if there is a function in C# would do this direct by passing bit values to it?


DataReader.GetBoolean(x)

or

Convert.ToBoolean(DataRow[x])


Depending on how are you performing the SQL queries it may depend. For example if you have a data reader you could directly read a boolean value:

using (var conn = new SqlConnection(ConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT isset_field FROM sometable";
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            bool isSet = reader.GetBoolean(0);
        }
    }
}


How are you extracting the fields from the database?

The SqlDataReader class has a GetBoolean method which does the translation for you:

bool yourBoolean = reader.GetBoolean(reader.GetOrdinal("Your_Bit_Column"));


GetBoolean will do this automatically.


SqlDataSource from ASP.NET 2.0 returns 0 and 1 for BIT fields.

SqlDataSource from ASP.NET 4.0 returns appropriate string - Boolean.TrueString ("True") or Boolean.FalseString ("False").

0

精彩评论

暂无评论...
验证码 换一张
取 消