Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In C#, using SqlDataReader, is there a way to read a boolean value from the DB?

while (reader.Read())
{
    destPath = reader["destination_path"].ToString();
    destFile = reader["destination_file"].ToString();
    createDir = reader["create_directory"].ToString();
    deleteExisting = Convert.ToBoolean(reader["delete_existing"]);
    skipIFolderDate = reader["skipifolderdate"].ToString();
    useTempFile = reader["useTempFile"].ToString();
    password = reader["password"].ToString();
}

In the code above, delete_existing is always a 1 or 0 in the DB. I read on MSDN that Convert.ToBoolean() does not accept a 1 or 0 as valid input. It only accepts true or false. Is there an alternative way to convert a DB value to a bool? Or do I need to do this outside of the SqlDataReader?

Also, I can not change the DB values, so please no answers saying, "Change the DB values from 1's and 0's to true's and false's."

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
578 views
Welcome To Ask or Share your Answers For Others

1 Answer

If the type of delete_existing is a sqlserver 'bit' type, you can do :

var i = reader.GetOrdinal("delete_existing"); // Get the field position
deleteExisting = reader.GetBoolean(i);

or (but it will crash if delete_existing can be DBNull)

deleteExisting = (bool)reader["delete_existing"];

or better, this onebelow is DBNull proof and returns false if the column is DBNull

deleteExisting = reader["delete_existing"] as bool? ?? false;

Otherwise if the database type is int :

deleteExisting = (reader["delete_existing"] as int? == 1) ? true : false;

or if it is a varchar

deleteExisting = (reader["delete_existing"] as string == "1") ? true : false;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...