1

I am trying to read nullable values from a database. Right now my code is converting null values to false. How can I modify my code to allow for null values?

Ap1ExamTaken = dr["AP1_ExamTaken"] != DBNull.Value && Convert.ToBoolean(dr["AP1_ExamTaken"]),

I would like values that are null to be shown as null and not false.

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
smuldr
  • 315
  • 1
  • 12

1 Answers1

3

You could use the conditional operator here, to set it to null if the value is DBNull.Value, or a non-nullable value otherwise:

Ap1ExamTaken = dr["AP1_ExamTaken"] == DBNull.Value ? null : (bool?) dr["AP1_ExamTaken"];

Note that this will throw an exception if dr["AP1_ExamTaken"] is a non-boolean, non-DBNull type, which I suspect is what you want.

You could write it more compactly as:

Ap1ExamTaken = dr["AP1_ExamTaken"] as bool?

... but then you'll end up with a null value if the value is some other type (a string, an integer etc) which I'd generally be alarmed about. (If my data doesn't have the shape I expect, I want to know ASAP.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194