C# convert bit to boolean

后端 未结 5 1582
北恋
北恋 2021-01-01 10:32

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 re

相关标签:
5条回答
  • 2021-01-01 10:53

    GetBoolean will do this automatically.

    0 讨论(0)
  • 2021-01-01 10:54
    DataReader.GetBoolean(x)
    

    or

    Convert.ToBoolean(DataRow[x])
    
    0 讨论(0)
  • 2021-01-01 11:01

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 11:10

    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"));
    
    0 讨论(0)
  • 2021-01-01 11:10

    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 讨论(0)
提交回复
热议问题